﻿#include "ITCatTableControl.h"

// 全局控件管理 - 统一管理所有控件和钩子
static std::vector<std::shared_ptr<ITCatTableControl>> g_Controls;  // 所有控件列表（使用智能指针）
static CRITICAL_SECTION g_csControls;  // 保护控件列表的临界区
static HHOOK g_GlobalKeyboardHook = NULL;  // 全局键盘钩子句柄

// 键盘钩子过程 - 静态方法
LRESULT CALLBACK ITCatTableControl::KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (nCode >= 0 && wParam == WM_KEYDOWN) {
        KBDLLHOOKSTRUCT* pKbhs = (KBDLLHOOKSTRUCT*)lParam;
        
        // 检查当前焦点窗口
        HWND hFocus = GetFocus();
        if (hFocus) {
            // 遍历所有控件，检查是否有正在编辑的控件需要拦截键盘消息
            EnterCriticalSection(&g_csControls);
            for (const auto& pCtrl : g_Controls) {
                if (pCtrl && pCtrl->m_hWnd) {
                    // 检查焦点是否在控件或其子窗口上
                    HWND hParent = GetParent(hFocus);
                    if (hParent == pCtrl->m_hWnd || hFocus == pCtrl->m_hWnd) {
                        // 如果控件正在编辑，拦截回车和ESC
                        if (pCtrl->IsEditing()) {
                            switch (pKbhs->vkCode) {
                            case VK_RETURN:
                                pCtrl->StopEditing(true);
                                LeaveCriticalSection(&g_csControls);
                                return 1; // 拦截消息
                                
                            case VK_ESCAPE:
                                pCtrl->StopEditing(false);
                                LeaveCriticalSection(&g_csControls);
                                return 1; // 拦截消息
                            }
                        }
                        break; // 找到匹配的控件，退出循环
                    }
                }
            }
            LeaveCriticalSection(&g_csControls);
        }
    }
    
    // 调用下一个钩子
    return CallNextHookEx(g_GlobalKeyboardHook, nCode, wParam, lParam);
}

// 编辑控件的子窗口过程
static LRESULT CALLBACK EditControlWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_KEYDOWN:
        switch (wParam) {
        case VK_RETURN: // 回车键提交编辑
            {
                // 获取父窗口（表格控件）
                HWND hParent = GetParent(hWnd);
                if (hParent) {
                    ITCatTableControl* pCtrl = (ITCatTableControl*)GetWindowLongPtr(hParent, GWLP_USERDATA);
                    if (pCtrl) {
                        pCtrl->StopEditing(true);
                    }
                }
            }
            return 0;
            
        case VK_ESCAPE: // ESC键取消编辑
            {
                // 获取父窗口（表格控件）
                HWND hParent = GetParent(hWnd);
                if (hParent) {
                    ITCatTableControl* pCtrl = (ITCatTableControl*)GetWindowLongPtr(hParent, GWLP_USERDATA);
                    if (pCtrl) {
                        pCtrl->StopEditing(false);
                    }
                }
            }
            return 0;
        }
        break;
        
    case WM_CHAR:
        // 拦截回车键和ESC键的字符消息
        switch (wParam) {
        case VK_RETURN: // 回车键
            {
                // 获取父窗口（表格控件）
                HWND hParent = GetParent(hWnd);
                if (hParent) {
                    ITCatTableControl* pCtrl = (ITCatTableControl*)GetWindowLongPtr(hParent, GWLP_USERDATA);
                    if (pCtrl) {
                        pCtrl->StopEditing(true);
                    }
                }
            }
            return 0;
        case VK_ESCAPE: // ESC键
            {
                // 获取父窗口（表格控件）
                HWND hParent = GetParent(hWnd);
                if (hParent) {
                    ITCatTableControl* pCtrl = (ITCatTableControl*)GetWindowLongPtr(hParent, GWLP_USERDATA);
                    if (pCtrl) {
                        pCtrl->StopEditing(false);
                    }
                }
            }
            return 0;
        }
        break;
    }
    
    // 调用默认的编辑控件窗口过程
    return CallWindowProc((WNDPROC)GetWindowLongPtr(hWnd, GWLP_USERDATA), hWnd, message, wParam, lParam);
}

void InitTableControl(HWND parent) {
    // 控件初始化函数
}

static LRESULT TableControlWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    ITCatTableControl* pCtrl = (ITCatTableControl*)GetWindowLongPtr(hWnd, GWLP_USERDATA);

    // 如果控件实例不存在，在第一条消息时自动创建
    if (pCtrl == NULL) {
        // 只在特定消息时创建实例，避免在窗口创建过程中过早创建
        if (message == WM_CREATE || message == WM_INITDIALOG || message == WM_PAINT ||
            message == WM_LBUTTONDOWN || message == WM_SETFOCUS) {

            // 创建新的控件实例（使用智能指针）
            auto pCtrlShared = std::make_shared<ITCatTableControl>();
            if (pCtrlShared) {
                // 设置窗口句柄
                pCtrlShared->m_hWnd = hWnd;

                // 绑定this指针到窗口
                SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pCtrlShared.get());

                // 将控件实例添加到全局列表并安装钩子
                EnterCriticalSection(&g_csControls);
                g_Controls.push_back(pCtrlShared);
                LeaveCriticalSection(&g_csControls);

                // 安装键盘钩子（现在钩子管理已集成到控件管理中）
                pCtrlShared->InstallKeyboardHook();

                // 设置窗口样式以减少闪烁
                LONG_PTR style = GetWindowLongPtr(hWnd, GWL_STYLE);
                style |= WS_CLIPCHILDREN; // 防止子窗口重绘时闪烁
                style |= WS_HSCROLL | WS_VSCROLL; // 启用滚动条
                SetWindowLongPtr(hWnd, GWL_STYLE, style);

                // 设置自定义边框样式
                LONG_PTR exStyle = GetWindowLongPtr(hWnd, GWL_EXSTYLE);
                exStyle &= ~WS_EX_CLIENTEDGE; // 移除系统客户区边缘，使用自定义边框
                exStyle |= WS_EX_WINDOWEDGE; // 确保有非客户区
                SetWindowLongPtr(hWnd, GWL_EXSTYLE, exStyle);

                //pCtrlShared->SetFlatBorder(TRUE);

                // 强制重绘窗口边框
                SetWindowPos(hWnd, NULL, 0, 0, 0, 0,
                    SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
                
                // 更新pCtrl指针
                pCtrl = pCtrlShared.get();
            }
        }

        // 如果仍然没有控件实例，调用默认处理
        if (pCtrl == NULL) {
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    return pCtrl->WndProc(hWnd, message, wParam, lParam);
}

HINSTANCE ITCatTableControl::s_hInstance = NULL;

ITCatTableControl::ITCatTableControl()
    : m_hWnd(NULL), columns(), rows()
{
    SetProperty(ITCatTablePropertiesEnum::CLR_BACKGROUND, RGB(255, 255, 255));
    SetProperty(ITCatTablePropertiesEnum::DWSTYLE, LVS_BORDER | LVS_GRID);

    SetProperty(ITCatTablePropertiesEnum::CLR_SELECTED, RGB(0, 120, 215));
    SetProperty(ITCatTablePropertiesEnum::CLR_SELECTED_UNFOCUSED,RGB(220, 220, 220)); 
    SetProperty(ITCatTablePropertiesEnum::CLR_HOT, RGB(232, 240, 254));
    SetProperty(ITCatTablePropertiesEnum::CLR_COLHEADER, RGB(240, 240, 240));
    SetProperty(ITCatTablePropertiesEnum::CLR_ROWHEADER, RGB(240, 240, 240));
    SetProperty(ITCatTablePropertiesEnum::CLR_GRID, RGB(230, 230, 240));
    SetProperty(ITCatTablePropertiesEnum::CLR_TEXT,RGB(0, 0, 0));  
    SetProperty(ITCatTablePropertiesEnum::CLR_COLHEADTEXT, RGB(0, 0, 0));  
    SetProperty(ITCatTablePropertiesEnum::CLR_ROWHEADTEXT, RGB(0, 0, 0));  
    SetProperty(ITCatTablePropertiesEnum::CLR_BORDER, RGB(128, 128, 128));  
    SetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT, 25);  
    SetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH, 75);  
    SetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT, 25);  
    SetProperty(ITCatTablePropertiesEnum::CELLMARGIN, 8);  // 设置单元格边距为8像素
    SetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE, ROWHEADER_TEXT);  // 默认显示文本

    SetBoolFlag(SHOW_COL_HEADER | SHOW_ROW_HEADER);
    
    // 初始化列宽调整信息
    m_ResizeInfo.isResizing = false;
    m_ResizeInfo.resizeColumnIndex = -1;
    m_ResizeInfo.startX = 0;
    m_ResizeInfo.originalWidth = 0;
    m_ResizeInfo.minWidth = 20;
    m_ResizeInfo.maxWidth = 1000;

    // 初始化 ImageList 相关
    m_hImageList = NULL;
    m_iconSize = 16;
    
    // 初始化钩子信息
    m_HookInfo.keyboardHook = NULL;
    m_HookInfo.hookInstalled = false;
    m_HookInfo.hookWindow = NULL;
}

// 钩子管理方法实现
bool ITCatTableControl::InstallKeyboardHook()
{
    if (m_HookInfo.hookInstalled) {
        return true; // 已经安装过了
    }
    
    // 如果全局钩子还没安装，先安装全局钩子
    if (!g_GlobalKeyboardHook) {
        g_GlobalKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProc, ITCatTableControl::s_hInstance, 0);
        if (!g_GlobalKeyboardHook) {
            return false;
        }
    }
    
    // 检查控件是否已经在列表中（使用智能指针的get()方法获取原始指针进行比较）
    EnterCriticalSection(&g_csControls);
    auto it = std::find_if(g_Controls.begin(), g_Controls.end(),
        [this](const std::shared_ptr<ITCatTableControl>& ptr) {
            return ptr.get() == this;
        });
    if (it == g_Controls.end()) {
        // 控件不在列表中，添加它（这里不需要添加，因为控件创建时已经添加了）
        // 智能指针会自动管理内存
    }
    LeaveCriticalSection(&g_csControls);
    
    m_HookInfo.hookInstalled = true;
    m_HookInfo.hookWindow = m_hWnd;
    
    return true;
}

void ITCatTableControl::UninstallKeyboardHook()
{
    if (!m_HookInfo.hookInstalled) {
        return; // 没有安装过
    }
    
    // 从控件列表中移除（使用智能指针的get()方法获取原始指针进行比较）
    EnterCriticalSection(&g_csControls);
    auto it = std::find_if(g_Controls.begin(), g_Controls.end(),
        [this](const std::shared_ptr<ITCatTableControl>& ptr) {
            return ptr.get() == this;
        });
    if (it != g_Controls.end()) {
        g_Controls.erase(it);
    }
    LeaveCriticalSection(&g_csControls);
    
    // 如果没有控件了，卸载全局钩子
    if (g_Controls.empty() && g_GlobalKeyboardHook) {
        UnhookWindowsHookEx(g_GlobalKeyboardHook);
        g_GlobalKeyboardHook = NULL;
    }
    
    m_HookInfo.hookInstalled = false;
    m_HookInfo.hookWindow = NULL;
}

// 析构函数 - 确保卸载钩子
ITCatTableControl::~ITCatTableControl()
{
    // 卸载键盘钩子（智能指针会自动管理内存，不需要手动清理）
    UninstallKeyboardHook();
}

BOOL ITCatTableControl::RegisterControlClass(HINSTANCE hInstance)
{
    // 初始化临界区
    InitializeCriticalSection(&g_csControls);

    // 初始化GDI+
    //GdiplusStartupInput gdiplusStartupInput;
    //ULONG_PTR gdiplusToken;
    //GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
    ITCatTableControl::s_hInstance = hInstance;

    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(wc));
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_GLOBALCLASS | CS_DBLCLKS;  // 添加CS_DBLCLKS支持双击
    wc.lpfnWndProc = (WNDPROC)TableControlWndProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszClassName = ITCAT_TABLE_CONTROL_CLASS;

    return RegisterClassEx(&wc) != 0;
}

BOOL ITCatTableControl::UnregisterControlClass(HINSTANCE hInstance)
{
    // 卸载所有钩子
    if (g_GlobalKeyboardHook) {
        UnhookWindowsHookEx(g_GlobalKeyboardHook);
        g_GlobalKeyboardHook = NULL;
    }
    
    // 清空控件列表（智能指针会自动管理内存）
    EnterCriticalSection(&g_csControls);
    g_Controls.clear();
    LeaveCriticalSection(&g_csControls);
    
    // 删除临界区
    DeleteCriticalSection(&g_csControls);

    return UnregisterClass(ITCAT_TABLE_CONTROL_CLASS, hInstance);
}

LRESULT ITCatTableControl::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message) {
        case WM_ERASEBKGND:
            // 返回TRUE表示我们已经处理了背景擦除，防止闪烁
            return TRUE;

        case WM_PAINT:
            //绘制控件
            OnDraw(hWnd);
            return 0;
        case WM_NCCALCSIZE: 
        {
            if (wParam) {
                LPNCCALCSIZE_PARAMS lpParams = reinterpret_cast<LPNCCALCSIZE_PARAMS>(lParam);
                int borderWidth = 1;
                // 预留左侧50像素，上侧30像素的非客户区区域
                lpParams->rgrc[0].left += borderWidth;
                lpParams->rgrc[0].right -= borderWidth;
                lpParams->rgrc[0].top += borderWidth;
                lpParams->rgrc[0].bottom -= borderWidth;
            }
            return DefWindowProc(hWnd, message, wParam, lParam);
        }

        case WM_NCPAINT: {
            // 绘制四个方向的边框和复选框
            DefWindowProc(hWnd, message, wParam, lParam);
            HDC hdc = GetWindowDC(hWnd);
            if (hdc) {
                RECT windowRect, clientRect;
                GetWindowRect(hWnd, &windowRect);
                GetClientRect(hWnd, &clientRect);

                // 转换为窗口坐标
                clientRect.right += clientRect.left;
                clientRect.bottom += clientRect.top;

                // 计算边框区域
                int width = windowRect.right - windowRect.left;
                int height = windowRect.bottom - windowRect.top;

                // 基础边框宽度
                int borderWidth = 1;

                RECT leftBorder = { 0, 0, borderWidth, height };
                RECT topBorder = { 0, 0, width, borderWidth };
                RECT rightBorder = { width - borderWidth, 0, width, height };
                RECT bottomBorder = { 0, height - borderWidth, width, height };

                // 确定边框颜色
                COLORREF borderColor = this->GetProperty(ITCatTablePropertiesEnum::CLR_BORDER);

                // 绘制四个方向的边框
                HBRUSH hBrush = CreateSolidBrush(borderColor);
                FillRect(hdc, &leftBorder, hBrush);
                FillRect(hdc, &topBorder, hBrush);
                FillRect(hdc, &rightBorder, hBrush);
                FillRect(hdc, &bottomBorder, hBrush);

                DeleteObject(hBrush);
                ReleaseDC(hWnd, hdc);
            }
            return 0;
        }

        case WM_SIZE:
            UpdateScrollInfo(hWnd);
            break;

        case WM_VSCROLL:
        {
            // 如果正在编辑，禁止滚动操作
            if (m_EditInfo.isEditing) {
                return 0; // 阻止滚动
            }
            
            // 处理垂直滚动
            int newScrollY = m_Info.scrollY;
            
            switch (LOWORD(wParam)) {
            case SB_LINEUP:
                // 向上滚动一行 - 找到当前最上面可见行的上一行
                // 如果已经在顶部，不再滚动
                if (m_Info.scrollY <= 0) {
                    newScrollY = 0;
                } else {
                    newScrollY = GetPreviousRowBoundary(m_Info.scrollY);
                }
                break;
            case SB_LINEDOWN:
                // 向下滚动一行 - 找到当前最上面可见行的下一行
                // 如果已经到达最大滚动位置，不再滚动
                {
                    RECT rect;
                    GetClientRect(hWnd, &rect);
                    int visibleHeight = rect.bottom - rect.top - GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT);
                    
                    if (m_Info.scrollY >= m_Info.maxScrollY) {
                        newScrollY = m_Info.maxScrollY;
                    } else {
                        newScrollY = GetNextRowBoundary(m_Info.scrollY, visibleHeight);
                        // 确保不超过最大滚动位置
                        if (newScrollY > m_Info.maxScrollY) {
                            newScrollY = m_Info.maxScrollY;
                        }
                    }
                }
                break;
            case SB_PAGEUP:
                // 向上滚动一页 - 计算可视区域能显示的行数，然后向上滚动那么多行
                {
                    RECT rect;
                    GetClientRect(hWnd, &rect);
                    int visibleHeight = rect.bottom - rect.top;
                    int visibleRows = 0;
                    int accumulatedHeight = 0;
                    
                    // 计算当前可视区域能显示多少行
                    for (size_t i = 0; i < rows.size(); ++i) {
                        int rowHeight = rows[i]->height; // 直接使用行的height属性
                        if (rowHeight == 0) rowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
                        if (accumulatedHeight + rowHeight <= visibleHeight) {
                            visibleRows++;
                            accumulatedHeight += rowHeight;
                        } else {
                            break;
                        }
                    }
                    
                    // 向上滚动visibleRows行
                    for (int i = 0; i < visibleRows; ++i) {
                        newScrollY = GetPreviousRowBoundary(newScrollY);
                        // 防止滚动到负数
                        if (newScrollY <= 0) {
                            newScrollY = 0;
                            break;
                        }
                    }
                }
                break;
            case SB_PAGEDOWN:
                // 向下滚动一页 - 计算可视区域能显示的行数，然后向下滚动那么多行
                {
                    RECT rect;
                    GetClientRect(hWnd, &rect);
                    int visibleHeight = rect.bottom - rect.top;
                    int visibleRows = 0;
                    int accumulatedHeight = 0;
                    
                    // 计算当前可视区域能显示多少行
                    for (size_t i = 0; i < rows.size(); ++i) {
                        int rowHeight = rows[i]->height; // 直接使用行的height属性
                        if (rowHeight == 0) rowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
                        if (accumulatedHeight + rowHeight <= visibleHeight) {
                            visibleRows++;
                            accumulatedHeight += rowHeight;
                        } else {
                            break;
                        }
                    }
                    
                                         // 向下滚动visibleRows行
                     for (int i = 0; i < visibleRows; ++i) {
                         newScrollY = GetNextRowBoundary(newScrollY, visibleHeight);
                         // 防止滚动超出范围
                         if (newScrollY >= m_Info.maxScrollY) {
                             newScrollY = m_Info.maxScrollY;
                             break;
                         }
                     }
                }
                break;
            case SB_THUMBPOSITION:
            case SB_THUMBTRACK:
                // 拖动滚动条时，需要对齐到行边界
                newScrollY = AlignScrollToRowBoundary(HIWORD(wParam));
                break;
            }

            // 限制滚动范围
            if (newScrollY < 0) newScrollY = 0;
            if (newScrollY > m_Info.maxScrollY) newScrollY = m_Info.maxScrollY;

            // 更新滚动位置
            m_Info.scrollY = newScrollY;

            // 更新滚动条位置
            SCROLLINFO si = { 0 };
            si.cbSize = sizeof(SCROLLINFO);
            si.fMask = SIF_POS;
            si.nPos = m_Info.scrollY;
            SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
            
            // 重绘控件
            InvalidateRect(hWnd, NULL, FALSE); // 使用FALSE避免擦除背景
        }
        return 0;

        case WM_HSCROLL:
        {
            // 如果正在编辑，禁止滚动操作
            if (m_EditInfo.isEditing) {
                return 0; // 阻止滚动
            }
            
            // 处理水平滚动
            switch (LOWORD(wParam)) {
            case SB_LINELEFT:
                m_Info.scrollX -= 20;
                break;
            case SB_LINERIGHT:
                m_Info.scrollX += 20;
                break;
            case SB_PAGELEFT:
                m_Info.scrollX -= 100;
                break;
            case SB_PAGERIGHT:
                m_Info.scrollX += 100;
                break;
            case SB_THUMBPOSITION:
            case SB_THUMBTRACK:
                m_Info.scrollX = HIWORD(wParam);
                break;
            }

            if (m_Info.scrollX < 0) m_Info.scrollX = 0;
            if (m_Info.scrollX > m_Info.maxScrollX) m_Info.scrollX = m_Info.maxScrollX;

            // 更新滚动条位置
            SCROLLINFO si = { 0 };
            si.cbSize = sizeof(SCROLLINFO);
            si.fMask = SIF_POS;
            si.nPos = m_Info.scrollX;
            SetScrollInfo(hWnd, SB_HORZ, &si, TRUE);

            InvalidateRect(hWnd, NULL, FALSE); // 使用FALSE避免擦除背景
        }
        return 0;

        case WM_LBUTTONDOWN:
        {
            int x = GET_X_LPARAM(lParam);
            int y = GET_Y_LPARAM(lParam);
            
            // 如果正在编辑，检查是否点击了编辑控件
            if (m_EditInfo.isEditing && m_EditInfo.editControl) {
                POINT pt = { x, y };
                ClientToScreen(m_hWnd, &pt);
                ScreenToClient(m_EditInfo.editControl, &pt);
                
                // 检查点击是否在编辑控件内
                RECT editRect;
                GetClientRect(m_EditInfo.editControl, &editRect);
                if (pt.x < 0 || pt.x >= editRect.right || pt.y < 0 || pt.y >= editRect.bottom) {
                    // 点击在编辑控件外，提交编辑
                    StopEditing(true);
                    return 0;
                }
            }
            
            // 检查是否在列标题区域
            int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
            
            // 根据行标题样式决定显示宽度
            int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
            int kHeaderWidth;
            if (GetBoolFlag(SHOW_ROW_HEADER)) {
                if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                    kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
                } else {
                    kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
                }
            } else {
                kHeaderWidth = 0;
            }
            
            // 检查是否点击了左上角的全选复选框
            if (y < kHeaderHeight && x < kHeaderWidth) {
                int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
                if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                    // 全选/取消全选
                    bool allSelected = IsAllRowsSelected();
                    SelectAllRows(!allSelected);
                    InvalidateRect(hWnd, NULL, FALSE);
                    return 0;
                }
            }
            
            if (y < kHeaderHeight && x >= kHeaderWidth) {
                // 在列标题区域，检查是否点击了列分隔线
                int currentX = kHeaderWidth - m_Info.scrollX;
                
                for (size_t i = 0; i < columns.size(); ++i) {
                    if (columns[i]->resizable) {
                        int colRight = currentX + columns[i]->width;
                        int resizeZone = 5; // 调整区域宽度
                        
                        if (abs(x - colRight) <= resizeZone) {
                            // 开始调整列宽
                            m_ResizeInfo.isResizing = true;
                            m_ResizeInfo.resizeColumnIndex = i;
                            m_ResizeInfo.startX = x;
                            m_ResizeInfo.originalWidth = columns[i]->width;
                            
                            // 设置鼠标捕获
                            SetCapture(hWnd);
                            return 0;
                        }
                    }
                    currentX += columns[i]->width;
                }
            }
            
            // 处理选中功能
            if (y >= kHeaderHeight && x >= kHeaderWidth) {
                // 在内容区域点击
                auto [rowIndex, colIndex] = GetRowColFromPoint(x, y);
                
                if (rowIndex >= 0 && colIndex >= 0) {
                    // 检查是否为分隔行，如果是则不允许选择
                    if (rowIndex < rows.size() && rows[rowIndex]->IsSeparatorRow()) {
                        return 0; // 分隔行不可选择
                    }
                    
                    // 检查是否按下了Ctrl键（多选）
                    bool isCtrlPressed = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
                    bool addToSelection = isCtrlPressed && m_SelectionInfo.isMultiSelect;
                    
                    if (m_SelectionInfo.isFullRowSelect) {
                        // 整行选择模式
                        SelectRow(rowIndex, addToSelection);
                    } else {
                        // 单元格选择模式
                        SelectCell(rowIndex, colIndex, addToSelection);
                    }
                    
                    return 0;
                }
            } else if (y >= kHeaderHeight && x < kHeaderWidth) {
                // 在行标题区域点击
                auto [rowIndex, colIndex] = GetRowColFromPoint(x, y);
                
                if (rowIndex >= 0) {
                    // 检查是否为分隔行，如果是则不允许选择
                    if (rowIndex < rows.size() && rows[rowIndex]->IsSeparatorRow()) {
                        return 0; // 分隔行不可选择
                    }
                    
                    // 检查行标题样式
                    int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
                    if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                        // 复选框模式：切换选中状态
                        rows[rowIndex]->isSelected = !rows[rowIndex]->isSelected;
                    } else {
                        // 普通模式：检查是否按下了Ctrl键（多选）
                        bool isCtrlPressed = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
                        bool addToSelection = isCtrlPressed && m_SelectionInfo.isMultiSelect;
                        
                        // 点击行标题总是选择整行
                        SelectRow(rowIndex, addToSelection);
                    }
                    return 0;
                }
            }
        }
        break;

        case WM_LBUTTONDBLCLK:
        {
            // 处理双击编辑功能
            int x = GET_X_LPARAM(lParam);
            int y = GET_Y_LPARAM(lParam);
            int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
            
            // 根据行标题样式决定显示宽度
            int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
            int kHeaderWidth;
            if (GetBoolFlag(SHOW_ROW_HEADER)) {
                if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                    kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
                } else {
                    kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
                }
            } else {
                kHeaderWidth = 0;
            }
            
            // 只在内容区域双击时启动编辑
            if (y >= kHeaderHeight && x >= kHeaderWidth) {
                auto [rowIndex, colIndex] = GetRowColFromPoint(x, y);
                
                if (rowIndex >= 0 && colIndex >= 0) {
                    // 检查是否为分隔行，如果是则不允许编辑
                    if (rowIndex < rows.size() && rows[rowIndex]->IsSeparatorRow()) {
                        return 0; // 分隔行不可编辑
                    }
                    
                    // 启动编辑
                    StartEditing(rowIndex, colIndex);
                    return 0;
                }
            }
        }
        break;

        case WM_RBUTTONDOWN:
        {
            int x = GET_X_LPARAM(lParam);
            int y = GET_Y_LPARAM(lParam);
            POINT clickPoint = { x, y };
            
            // 检查是否在列标题区域
            int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
            
            // 根据行标题样式决定显示宽度
            int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
            int kHeaderWidth;
            if (GetBoolFlag(SHOW_ROW_HEADER)) {
                if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                    kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
                } else {
                    kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
                }
            } else {
                kHeaderWidth = 0;
            }
            
            // 确定点击位置并触发相应事件
            if (y < kHeaderHeight && x < kHeaderWidth) {
                // 左上角区域
                FireRightClickEvent(-1, -1, clickPoint);
            } else if (y < kHeaderHeight && x >= kHeaderWidth) {
                // 列标题区域
                int currentX = kHeaderWidth - m_Info.scrollX;
                int colIndex = -1;
                
                for (size_t i = 0; i < columns.size(); ++i) {
                    if (x >= currentX && x < currentX + columns[i]->width) {
                        colIndex = static_cast<int>(i);
                        break;
                    }
                    currentX += columns[i]->width;
                }
                
                if (colIndex >= 0) {
                    FireRightClickEvent(-2, colIndex, clickPoint);  // 列标题区域，传递列索引
                } else {
                    FireRightClickEvent(-2, -1, clickPoint);  // 列标题但无法确定具体列
                }
            } else if (y >= kHeaderHeight && x < kHeaderWidth) {
                // 行标题区域
                auto [rowIndex, colIndex] = GetRowColFromPoint(x, y);
                if (rowIndex >= 0) {
                    FireRightClickEvent(rowIndex, -2, clickPoint);  // 行标题区域，传递行索引
                } else {
                    FireRightClickEvent(-1, -2, clickPoint);  // 行标题但无法确定具体行
                }
            } else if (y >= kHeaderHeight && x >= kHeaderWidth) {
                // 内容区域
                auto [rowIndex, colIndex] = GetRowColFromPoint(x, y);
                if (rowIndex >= 0 && colIndex >= 0) {
                    FireRightClickEvent(rowIndex, colIndex, clickPoint);
                } else {
                    FireRightClickEvent(-1, -1, clickPoint);  // 无效区域
                }
            } else {
                // 其他区域
                FireRightClickEvent(-1, -1, clickPoint);
            }
            
            return 0;
        }
        break;

        case WM_KEYDOWN:
        {
            // 处理键盘消息
            if (m_EditInfo.isEditing) {
                // 如果正在编辑，处理编辑控件的键盘事件
                HandleEditKeyDown(wParam);
                return 0;
            } else {
                // 如果不在编辑状态，处理表格的键盘事件
                switch (wParam) {
                case VK_F2: // F2键启动编辑
                    if (m_SelectionInfo.focusedCellRow >= 0 && m_SelectionInfo.focusedCellCol >= 0) {
                        StartEditing(m_SelectionInfo.focusedCellRow, m_SelectionInfo.focusedCellCol);
                    }
                    return 0;
                }
            }
        }
        break;

        case WM_KILLFOCUS:
        {
            // 失去焦点时，如果正在编辑则提交编辑
            if (m_EditInfo.isEditing) {
                HWND newFocus = (HWND)wParam;
                // 检查新焦点是否是编辑控件本身
                if (newFocus != m_EditInfo.editControl) {
                    StopEditing(true); // 提交编辑
                }
            }
        }
        break;

        case WM_CHAR:
        {
            // 处理字符消息，防止编辑状态下的回车键传递给对话框
            if (m_EditInfo.isEditing) {
                switch (wParam) {
                case VK_RETURN: // 回车键
                case VK_ESCAPE: // ESC键
                    return 0; // 阻止消息传递给父窗口
                }
            }
        }
        break;

        case WM_COMMAND:
        {
            // 拦截编辑控件的命令消息
            if (m_EditInfo.isEditing && m_EditInfo.editControl && 
                (HWND)lParam == m_EditInfo.editControl) {
                switch (HIWORD(wParam)) {
                case EN_UPDATE:
                case EN_CHANGE:
                    return 0; // 处理编辑控件的更新消息
                }
            }
        }
        break;

        case WM_MOUSEMOVE:
        {
            if (m_ResizeInfo.isResizing) {
                int x = GET_X_LPARAM(lParam);
                int deltaX = x - m_ResizeInfo.startX;
                int newWidth = m_ResizeInfo.originalWidth + deltaX;
                
                // 限制列宽范围
                if (newWidth < m_ResizeInfo.minWidth) newWidth = m_ResizeInfo.minWidth;
                if (newWidth > m_ResizeInfo.maxWidth) newWidth = m_ResizeInfo.maxWidth;
                
                // 更新列宽
                if (m_ResizeInfo.resizeColumnIndex >= 0 && m_ResizeInfo.resizeColumnIndex < columns.size()) {
                    columns[m_ResizeInfo.resizeColumnIndex]->width = newWidth;
                    
                    // 更新滚动信息并重绘
                    UpdateScrollInfo(hWnd);
                    InvalidateRect(hWnd, NULL, FALSE);
                }
                return 0;
            } else {
                // 检查鼠标是否在列分隔线上，如果是则改变光标
                int x = GET_X_LPARAM(lParam);
                int y = GET_Y_LPARAM(lParam);
                
                int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
                
                // 根据行标题样式决定显示宽度
                int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
                int kHeaderWidth;
                if (GetBoolFlag(SHOW_ROW_HEADER)) {
                    if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                        kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
                    } else {
                        kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
                    }
                } else {
                    kHeaderWidth = 0;
                }
                
                if (y < kHeaderHeight && x >= kHeaderWidth) {
                    int currentX = kHeaderWidth - m_Info.scrollX;
                    bool shouldShowResizeCursor = false;
                    
                    for (size_t i = 0; i < columns.size(); ++i) {
                        if (columns[i]->resizable) {
                            int colRight = currentX + columns[i]->width;
                            int resizeZone = 5;
                            
                            if (abs(x - colRight) <= resizeZone) {
                                shouldShowResizeCursor = true;
                                break;
                            }
                        }
                        currentX += columns[i]->width;
                    }
                    
                    if (shouldShowResizeCursor) {
                        SetCursor(LoadCursor(NULL, IDC_SIZEWE));
                    } else {
                        SetCursor(LoadCursor(NULL, IDC_ARROW));
                    }
                }
            }
        }
        break;

        case WM_LBUTTONUP:
        {
            if (m_ResizeInfo.isResizing) {
                // 结束调整列宽
                m_ResizeInfo.isResizing = false;
                m_ResizeInfo.resizeColumnIndex = -1;
                
                // 释放鼠标捕获
                ReleaseCapture();
                return 0;
            }
        }
        break;

        case WM_CAPTURECHANGED:
        {
            // 如果失去鼠标捕获，结束调整
            if (m_ResizeInfo.isResizing) {
                m_ResizeInfo.isResizing = false;
                m_ResizeInfo.resizeColumnIndex = -1;
            }
        }
        break;

        case WM_MOUSEWHEEL:
        {
            // 处理鼠标滚轮消息
            int delta = GET_WHEEL_DELTA_WPARAM(wParam);
            int scrollLines = abs(delta) / WHEEL_DELTA;  // 获取滚动行数
            
            // 确定滚动方向
            bool scrollUp = (delta > 0);
            
            // 获取当前滚动位置
            int currentScrollY = m_Info.scrollY;
            int newScrollY = currentScrollY;
            
            // 计算新的滚动位置
            if (scrollUp) {
                // 向上滚动
                for (int i = 0; i < scrollLines; ++i) {
                    newScrollY = GetPreviousRowBoundary(newScrollY);
                }
            } else {
                // 向下滚动
                RECT clientRect;
                GetClientRect(hWnd, &clientRect);
                int visibleHeight = clientRect.bottom - clientRect.top;
                
                // 如果有列标题，需要减去列标题高度
                if (GetBoolFlag(SHOW_COL_HEADER)) {
                    visibleHeight -= GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT);
                }
                
                for (int i = 0; i < scrollLines; ++i) {
                    newScrollY = GetNextRowBoundary(newScrollY, visibleHeight);
                }
            }
            
            // 限制滚动范围
            if (newScrollY < 0) newScrollY = 0;
            if (newScrollY > m_Info.maxScrollY) newScrollY = m_Info.maxScrollY;
            
            // 如果滚动位置发生变化，更新滚动信息并重绘
            if (newScrollY != currentScrollY) {
                m_Info.scrollY = newScrollY;
                
                // 更新滚动条
                SCROLLINFO si;
                si.cbSize = sizeof(SCROLLINFO);
                si.fMask = SIF_POS;
                si.nPos = newScrollY;
                SetScrollInfo(hWnd, SB_VERT, &si, TRUE);
                
                // 重绘控件
                InvalidateRect(hWnd, NULL, FALSE);
                
                return 0;  // 消息已处理
            }
        }
        break;
    }
    return DefWindowProc(hWnd,message,wParam,lParam);
}

ITCatTableColumn* ITCatTableControl::AddColumn(const std::wstring& title, int width)
{
    auto col = std::make_unique<ITCatTableColumn>(this);
    col->setText(title.c_str());
    col->width = width;
    ITCatTableColumn* pCol = col.get();
    columns.push_back(std::move(col));
    // 给所有已存在的行补一个空单元格
    for (auto& row : rows) {
        row->cells.push_back(std::make_unique<ITCatTableCell>(row.get()));
    }
    // 更新滚动信息
    UpdateScrollInfo(m_hWnd);
    return pCol;
}

void ITCatTableControl::AddRow(const std::wstring& rowTitle, const std::vector<std::wstring>& cellTexts)
{
    auto row = std::make_unique<ITCatTableRow>(this);
    row->setText(rowTitle.c_str());
    // 填充单元格内容
    for (size_t j = 0; j < columns.size() && j < cellTexts.size(); ++j) {
        row->cells[j]->setText(cellTexts[j].c_str());
    }
    rows.push_back(std::move(row));
    // 更新滚动信息
    UpdateScrollInfo(m_hWnd);
}

void ITCatTableControl::SetRowHeight(size_t rowIndex, int height)
{
    if (rowIndex < rows.size()) {
        rows[rowIndex]->height = height;
        // 更新滚动信息
        UpdateScrollInfo(m_hWnd);
        // 触发重绘
        if (m_hWnd) {
            InvalidateRect(m_hWnd, NULL, FALSE);
        }
    }
}

void ITCatTableControl::SetRowHeaderStyle(int style)
{
    SetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE, style);
    // 触发重绘
    if (m_hWnd) {
        InvalidateRect(m_hWnd, NULL, FALSE);
    }
}

void ITCatTableControl::SetRowHeaderVisible(bool visible)
{
    if (visible) {
        SetBoolFlag(SHOW_ROW_HEADER);
    } else {
        ClearBoolFlag(SHOW_ROW_HEADER);
    }
    
    // 更新滚动信息
    UpdateScrollInfo(m_hWnd);
    
    // 触发重绘
    if (m_hWnd) {
        InvalidateRect(m_hWnd, NULL, FALSE);
    }
}

void ITCatTableControl::SetRowAsSeparator(size_t rowIndex, bool isSeparator)
{
    if (rowIndex < rows.size()) {
        rows[rowIndex]->SetSeparatorRow(isSeparator);
        
        // 如果是分隔行，自动合并所有列
        if (isSeparator && !columns.empty()) {
            // 检查上一行是否有 rowspan > 1 的单元格，如果有则清掉
            if (rowIndex > 0) {
                for (size_t colIdx = 0; colIdx < columns.size(); ++colIdx) {
                    if (rows[rowIndex - 1]->cells[colIdx]->rowspan > 1) {
                        // 清掉上一行的 rowspan
                        SetCellRowspan(rowIndex - 1, colIdx, 1);
                    }
                }
            }
            
            // 设置第一列为跨所有列的合并单元格
            SetCellColspan(rowIndex, 0, static_cast<int>(columns.size()));
            
            // 设置其他列为被合并状态
            for (size_t colIdx = 1; colIdx < columns.size(); ++colIdx) {
                SetCellColspan(rowIndex, colIdx, 0);
            }
            
            // 设置分隔行不可选择
            rows[rowIndex]->isSelectEnable = false;
            
            // 清空行标题文本
            rows[rowIndex]->setText(L"");
        } else if (!isSeparator) {
            // 如果不是分隔行，恢复所有单元格为正常状态
            for (size_t colIdx = 0; colIdx < columns.size(); ++colIdx) {
                SetCellColspan(rowIndex, colIdx, 1);
            }
            
            // 恢复行可选择状态
            rows[rowIndex]->isSelectEnable = true;
        }
        
        // 触发重绘
        if (m_hWnd) {
            InvalidateRect(m_hWnd, NULL, FALSE);
        }
    }
}

// 设置分隔行对齐方式
void ITCatTableControl::SetSeparatorAlignment(int alignment) {
    SetProperty(ITCatTablePropertiesEnum::SEPARATOR_ALIGNMENT, alignment);
    // 触发重绘
    if (m_hWnd) {
        InvalidateRect(m_hWnd, NULL, FALSE);
    }
}

// 颜色设置方法实现
void ITCatTableControl::SetRowBackgroundColor(size_t rowIndex, COLORREF color)
{
    if (rowIndex < rows.size()) {
        rows[rowIndex]->SetBackgroundColor(color);
        // 触发重绘
        if (m_hWnd) {
            InvalidateRect(m_hWnd, NULL, FALSE);
        }
    }
}

void ITCatTableControl::SetRowTextColor(size_t rowIndex, COLORREF color)
{
    if (rowIndex < rows.size()) {
        rows[rowIndex]->SetCustomTextColor(color);
        // 触发重绘
        if (m_hWnd) {
            InvalidateRect(m_hWnd, NULL, FALSE);
        }
    }
}

void ITCatTableControl::SetCellBackgroundColor(size_t rowIndex, size_t colIndex, COLORREF color)
{
    if (rowIndex < rows.size() && colIndex < rows[rowIndex]->cells.size()) {
        rows[rowIndex]->cells[colIndex]->SetBackgroundColor(color);
        // 触发重绘
        if (m_hWnd) {
            InvalidateRect(m_hWnd, NULL, FALSE);
        }
    }
}

void ITCatTableControl::SetCellTextColor(size_t rowIndex, size_t colIndex, COLORREF color)
{
    if (rowIndex < rows.size() && colIndex < rows[rowIndex]->cells.size()) {
        rows[rowIndex]->cells[colIndex]->SetCustomTextColor(color);
        // 触发重绘
        if (m_hWnd) {
            InvalidateRect(m_hWnd, NULL, FALSE);
        }
    }
}

void ITCatTableControl::OnDraw(HWND hWnd)
{
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hWnd, &ps);
    RECT clientRect;
    GetClientRect(hWnd, &clientRect);
    int defaultRowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
    int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
    
    // 根据行标题样式决定显示宽度
    int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
    int kHeaderWidth;
    if (GetBoolFlag(SHOW_ROW_HEADER)) {
        if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
            kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
        } else {
            kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
        }
    } else {
        kHeaderWidth = 0;
    }

    // 使用滚动信息
    int scrollY = m_Info.scrollY; // 当前垂直滚动像素偏移
    int scrollX = m_Info.scrollX; // 当前水平滚动像素偏移
    


    // 创建内存DC进行双缓冲绘制
    HDC memDC = CreateCompatibleDC(hdc);
    HBITMAP memBitmap = CreateCompatibleBitmap(hdc, clientRect.right - clientRect.left, clientRect.bottom - clientRect.top);
    HBITMAP oldBitmap = (HBITMAP)SelectObject(memDC, memBitmap);

    // 绘制背景
    HBRUSH hBrush = CreateSolidBrush(GetProperty(ITCatTablePropertiesEnum::CLR_BACKGROUND));
    FillRect(memDC, &clientRect, hBrush);
    DeleteObject(hBrush);

    // 0. 先绘制左上角交叉格子（如果有行标题和列标题）- 不包含在裁剪区内
    if (!columns.empty() && !rows.empty() && GetBoolFlag(SHOW_COL_HEADER) && GetBoolFlag(SHOW_ROW_HEADER)) {
        RECT cornerRect = { 0, 0, kHeaderWidth, kHeaderHeight };
        
        // 填充左上角背景色（使用列标题背景色）
        HBRUSH hCornerBrush = CreateSolidBrush(GetProperty(ITCatTablePropertiesEnum::CLR_COLHEADER));
        FillRect(memDC, &cornerRect, hCornerBrush);
        DeleteObject(hCornerBrush);
        
        // 如果行标题是复选框模式，绘制全选复选框
        int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
        if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
            DrawCheckBox(memDC, cornerRect, IsAllRowsSelected(), true);
        }
        
        // 只画右边和下边的线
        HPEN hPen = CreatePen(PS_SOLID, 1, GetProperty(ITCatTablePropertiesEnum::CLR_GRID));
        HPEN hOldPen = (HPEN)SelectObject(memDC, hPen);
        MoveToEx(memDC, cornerRect.right - 1, cornerRect.top, NULL);
        LineTo(memDC, cornerRect.right - 1, cornerRect.bottom - 1);
        MoveToEx(memDC, cornerRect.left, cornerRect.bottom - 1, NULL);
        LineTo(memDC, cornerRect.right, cornerRect.bottom - 1);
        SelectObject(memDC, hOldPen);
        DeleteObject(hPen);
    }

    // 1. 绘制列标题区
    if (GetBoolFlag(SHOW_COL_HEADER)) {
        HRGN hColHeaderRgn = CreateRectRgn(kHeaderWidth, 0, clientRect.right, kHeaderHeight);
        SelectClipRgn(memDC, hColHeaderRgn);
        
        int x = kHeaderWidth - scrollX;
        int y = 0;
        // 绘制所有列标题，但只绘制可见的
        for (size_t i = 0; i < columns.size(); ++i) {
            // 只绘制可见的列
            if (x + columns[i]->width > 0 && x < clientRect.right) {
                RECT colRect = { x, y, x + columns[i]->width, y + kHeaderHeight};
                
                // 填充列标题背景色
                HBRUSH hColHeaderBrush = CreateSolidBrush(GetProperty(ITCatTablePropertiesEnum::CLR_COLHEADER));
                FillRect(memDC, &colRect, hColHeaderBrush);
                DeleteObject(hColHeaderBrush);
                
            HFONT hNewFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
            HFONT hOldFont = (HFONT)SelectObject(memDC, hNewFont);
            SetTextColor(memDC, GetProperty(ITCatTablePropertiesEnum::CLR_COLHEADTEXT));
            SetBkMode(memDC, TRANSPARENT);
            DrawTextW(memDC, columns[i]->getText(), -1, &colRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
            SelectObject(memDC, hOldFont);
            // 只画右边和下边的线
            HPEN hPen = CreatePen(PS_SOLID, 1, GetProperty(ITCatTablePropertiesEnum::CLR_GRID));
            HPEN hOldPen = (HPEN)SelectObject(memDC, hPen);
            MoveToEx(memDC, colRect.right - 1, colRect.top, NULL);
            LineTo(memDC, colRect.right - 1, colRect.bottom - 1);
            MoveToEx(memDC, colRect.left, colRect.bottom - 1, NULL);
            LineTo(memDC, colRect.right, colRect.bottom - 1);
            SelectObject(memDC, hOldPen);
            DeleteObject(hPen);
            }
            x += columns[i]->width;
        }
        DeleteObject(hColHeaderRgn);
    }

    // 2. 绘制行标题区
    if (GetBoolFlag(SHOW_ROW_HEADER)) {
        HRGN hRowHeaderRgn = CreateRectRgn(0, kHeaderHeight, kHeaderWidth, clientRect.bottom);
        SelectClipRgn(memDC, hRowHeaderRgn);
        
        int y = kHeaderHeight - scrollY; // 应用垂直滚动偏移
        // 绘制所有行标题，但只绘制可见的
        for (size_t rowIdx = 0; rowIdx < rows.size(); ++rowIdx) {
            int kRowHeight = rows[rowIdx]->height; // 直接使用行的height属性
            if (kRowHeight == 0) kRowHeight = defaultRowHeight; // 如果行没有设置高度，使用默认高度
            
            // 只绘制可见的行
            if (y + kRowHeight > 0 && y < clientRect.bottom) {
                RECT rowHeaderRect = { 0, y, kHeaderWidth, y + kRowHeight };
                
                // 检查是否为分隔行
                bool isSeparatorRow = rows[rowIdx]->IsSeparatorRow();
                
                // 检查行是否被选中
                bool isRowSelected = rows[rowIdx]->isSelected;
                
                // 根据选中状态、分隔行状态和颜色继承系统选择背景色
                COLORREF rowHeaderColor;
                if (isRowSelected) {
                    rowHeaderColor = GetProperty(ITCatTablePropertiesEnum::CLR_SELECTED);
                } else {
                    // 行标题背景色继承：行 -> 默认
                    if (rows[rowIdx]->HasCustomBackgroundColor()) {
                        rowHeaderColor = rows[rowIdx]->GetBackgroundColor();
                    } else {
                        rowHeaderColor = GetProperty(ITCatTablePropertiesEnum::CLR_ROWHEADER);
                    }
                }
                
                // 填充行标题背景色
                HBRUSH hRowHeaderBrush = CreateSolidBrush(rowHeaderColor);
                FillRect(memDC, &rowHeaderRect, hRowHeaderBrush);
                DeleteObject(hRowHeaderBrush);
                
                HFONT hNewFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
                HFONT hOldFont = (HFONT)SelectObject(memDC, hNewFont);
                
                // 行标题文本颜色继承：行 -> 默认
                COLORREF textColor;
                if (rows[rowIdx]->HasCustomTextColor()) {
                    textColor = rows[rowIdx]->GetTextColor();
                } else {
                    textColor = GetProperty(ITCatTablePropertiesEnum::CLR_ROWHEADTEXT);
                }
                SetTextColor(memDC, textColor);
                SetBkMode(memDC, TRANSPARENT);
                
                // 根据行标题样式决定显示内容
                int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
                const wchar_t* displayText = nullptr;
                
                if (isSeparatorRow) {
                    // 分隔行不显示任何内容
                    displayText = L"";
                } else if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
                    // 显示复选框
                    DrawCheckBox(memDC, rowHeaderRect, rows[rowIdx]->isSelected, true);
                } else if (rowHeaderStyle == ITCatTableBase::ROWHEADER_ICON) {
                    // 显示图标
                    if (rows[rowIdx]->iconIndex >= 0 && HasImageList()) {
                        DrawIcon(memDC, rows[rowIdx]->iconIndex, rowHeaderRect);
                    }
                } else if (rowHeaderStyle == ITCatTableBase::ROWHEADER_NUMBER) {
                    // 显示序号
                    static wchar_t numberBuffer[32];
                    swprintf_s(numberBuffer, L"%d", (int)(rowIdx + 1));
                    displayText = numberBuffer;
                } else {
                    // 默认显示文本
                    displayText = rows[rowIdx]->getText();
                }
                
                // 如果不是复选框模式且不是图标模式且不是分隔行，才绘制文本
                if (rowHeaderStyle != ITCatTableBase::ROWHEADER_CHECKBOX && 
                    rowHeaderStyle != ITCatTableBase::ROWHEADER_ICON &&
                    !isSeparatorRow) {
                    DrawTextW(memDC, displayText, -1, &rowHeaderRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
                }
                SelectObject(memDC, hOldFont);
                // 只画右边和下边的线（分隔行不绘制下边框，避免重复）
                HPEN hPen = CreatePen(PS_SOLID, 1, GetProperty(ITCatTablePropertiesEnum::CLR_GRID));
                HPEN hOldPen = (HPEN)SelectObject(memDC, hPen);
                MoveToEx(memDC, rowHeaderRect.right - 1, rowHeaderRect.top, NULL);
                LineTo(memDC, rowHeaderRect.right - 1, rowHeaderRect.bottom - 1);
                // 分隔行不绘制下边框，避免与内容区域重复
                if (!isSeparatorRow) {
                    MoveToEx(memDC, rowHeaderRect.left, rowHeaderRect.bottom - 1, NULL);
                    LineTo(memDC, rowHeaderRect.right, rowHeaderRect.bottom - 1);
                }
                SelectObject(memDC, hOldPen);
                DeleteObject(hPen);
            }
            y += kRowHeight;
        }
        DeleteObject(hRowHeaderRgn);
    }

    // 3. 绘制表格内容区
    HRGN hContentRgn = CreateRectRgn(kHeaderWidth, kHeaderHeight, clientRect.right, clientRect.bottom);
    SelectClipRgn(memDC, hContentRgn);
    
    int y = kHeaderHeight - scrollY; // 应用垂直滚动偏移
    // 绘制所有内容，但只绘制可见的
    for (size_t rowIdx = 0; rowIdx < rows.size(); ++rowIdx) {
        int kRowHeight = rows[rowIdx]->height; // 直接使用行的height属性
        if (kRowHeight == 0) kRowHeight = defaultRowHeight; // 如果行没有设置高度，使用默认高度
        
        // 只绘制可见的行
        if (y + kRowHeight > 0 && y < clientRect.bottom) {
            // 检查是否为分隔行
            bool isSeparatorRow = rows[rowIdx]->IsSeparatorRow();
            
            int x = kHeaderWidth - scrollX;
            // 绘制所有列，但只绘制可见的
            for (size_t colIdx = 0; colIdx < columns.size(); ++colIdx) {
                // 检查单元格是否应该被绘制（不是被合并的）
                if (!IsCellVisible(rowIdx, colIdx)) {
                    x += columns[colIdx]->width;
                    continue;
                }
                
                // 获取单元格的实际绘制矩形（考虑合并）
                RECT cellRect = GetCellRect(rowIdx, colIdx);
                
                // 应用滚动偏移
                cellRect.left -= scrollX;
                cellRect.right -= scrollX;
                cellRect.top -= scrollY;
                cellRect.bottom -= scrollY;
                
                // 只绘制可见的单元格
                if (cellRect.right > 0 && cellRect.left < clientRect.right && 
                    cellRect.bottom > 0 && cellRect.top < clientRect.bottom) {
                    
                    // 获取单元格引用
                    auto& cell = rows[rowIdx]->cells[colIdx];
                    
                    // 分隔行特殊处理：只在第一个单元格绘制
                    if (isSeparatorRow && colIdx > 0) {
                        x += columns[colIdx]->width;
                        continue;
                    }
                    
                    // 检查单元格是否被选中（分隔行不能被选中）
                    bool isCellSelected = cell->isSelected && !isSeparatorRow;
                    bool isRowSelected = rows[rowIdx]->isSelected && !isSeparatorRow;
                    
                    // 根据选中状态、分隔行状态和颜色继承系统选择背景色
                    COLORREF backgroundColor;
                    if (isCellSelected || (isRowSelected && this->m_SelectionInfo.isFullRowSelect)) {
                        backgroundColor = GetProperty(ITCatTablePropertiesEnum::CLR_SELECTED);
                    } else {
                        // 颜色继承系统：单元格 -> 行 -> 默认
                        if (cell->HasCustomBackgroundColor()) {
                            backgroundColor = cell->GetBackgroundColor();
                        } else if (rows[rowIdx]->HasCustomBackgroundColor()) {
                            backgroundColor = rows[rowIdx]->GetBackgroundColor();
                        } else {
                            backgroundColor = GetProperty(ITCatTablePropertiesEnum::CLR_BACKGROUND);
                        }
                    }
                    
                    // 填充单元格背景色
                    HBRUSH hCellBrush = CreateSolidBrush(backgroundColor);
                    FillRect(memDC, &cellRect, hCellBrush);
                    DeleteObject(hCellBrush);
                    
                    // 绘制单元格文本 - 只有主单元格才绘制文本，且不在编辑状态
                    if (cell->colspan > 0 && cell->rowspan > 0 && 
                        !(m_EditInfo.isEditing && m_EditInfo.editRow == static_cast<int>(rowIdx) && m_EditInfo.editCol == static_cast<int>(colIdx))) {
                        
                        // 如果是第一个单元格且有图标，且行标题不是图标模式，先绘制图标
                        int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
                        bool hasIcon = (colIdx == 0 && rows[rowIdx]->iconIndex >= 0 && HasImageList() && 
                                       rowHeaderStyle != ITCatTableBase::ROWHEADER_ICON);
                        if (hasIcon) {
                            DrawIcon(memDC, rows[rowIdx]->iconIndex, cellRect);
                        }
                        
                        HFONT hNewFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
                        HFONT hOldFont = (HFONT)SelectObject(memDC, hNewFont);
                        
                        // 根据是否为分隔行和颜色继承系统设置文本颜色和样式
                        if (isSeparatorRow) {
                            // 分隔行使用粗体字体，但颜色继承系统的规则
                            COLORREF textColor;
                            if (cell->HasCustomTextColor()) {
                                textColor = cell->GetTextColor();
                            } else if (rows[rowIdx]->HasCustomTextColor()) {
                                textColor = rows[rowIdx]->GetTextColor();
                            } else {
                                textColor = GetProperty(ITCatTablePropertiesEnum::CLR_TEXT);
                            }
                            SetTextColor(memDC, textColor);
                            SetBkMode(memDC, TRANSPARENT);
                            
                            // 分隔行使用粗体字体
                            HFONT hBoldFont = CreateFont(16, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
                                DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
                                DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Microsoft YaHei");
                            HFONT hOldFont = (HFONT)SelectObject(memDC, hBoldFont);
                            
                            // 分隔行使用可配置的对齐方式
                            UINT textAlign = DT_VCENTER | DT_SINGLELINE;
                            int separatorAlignment = GetProperty(ITCatTablePropertiesEnum::SEPARATOR_ALIGNMENT);
                            
                            // 获取单元格边距
                            int cellMargin = GetProperty(ITCatTablePropertiesEnum::CELLMARGIN);
                            
                            // 根据对齐方式调整文本绘制区域
                            RECT textRect = cellRect;
                            switch (separatorAlignment) {
                                case ITCatTableBase::LVCA_LEFT:
                                    textAlign |= DT_LEFT;
                                    textRect.left += cellMargin;  // 左对齐时左边留边距
                                    break;
                                case ITCatTableBase::LVCA_RIGHT:
                                    textAlign |= DT_RIGHT;
                                    textRect.right -= cellMargin;  // 右对齐时右边留边距
                                    break;
                                default:  // LVCA_CENTER 或未设置
                                    textAlign |= DT_CENTER;
                                    // 居中对齐不需要调整边距
                                    break;
                            }
                            DrawTextW(memDC, cell->getText(), -1, &textRect, textAlign);
                            SelectObject(memDC, hOldFont);
                            DeleteObject(hBoldFont);
                        } else {
                            // 颜色继承系统：单元格 -> 行 -> 默认
                            COLORREF textColor;
                            if (cell->HasCustomTextColor()) {
                                textColor = cell->GetTextColor();
                            } else if (rows[rowIdx]->HasCustomTextColor()) {
                                textColor = rows[rowIdx]->GetTextColor();
                            } else {
                                textColor = GetProperty(ITCatTablePropertiesEnum::CLR_TEXT);
                            }
                            SetTextColor(memDC, textColor);
                            SetBkMode(memDC, TRANSPARENT);
                            
                            // 确定文本对齐方式
                            UINT textAlign = DT_VCENTER | DT_SINGLELINE;
                            
                            // 获取单元格边距
                            int cellMargin = GetProperty(ITCatTablePropertiesEnum::CELLMARGIN);
                            
                            // 如果有图标，调整文本绘制区域（图标后面）并使用左对齐
                            RECT textRect = cellRect;
                            if (hasIcon) {
                                textRect.left += m_iconSize + 10;  // 图标宽度 + 10像素间距
                                textAlign |= DT_LEFT;
                            } else {
                                // 使用列中定义的对齐方式
                                if (colIdx < columns.size()) {
                                    switch (columns[colIdx]->alignment) {
                                        case ITCatTableBase::LVCA_LEFT:
                                            textAlign |= DT_LEFT;
                                            textRect.left += cellMargin;  // 左对齐时左边留边距
                                            break;
                                        case ITCatTableBase::LVCA_RIGHT:
                                            textAlign |= DT_RIGHT;
                                            textRect.right -= cellMargin;  // 右对齐时右边留边距
                                            break;
                                        default:  // LVCA_CENTER 或未设置
                                            textAlign |= DT_CENTER;
                                            // 居中对齐不需要调整边距
                                            break;
                                    }
                                } else {
                                    textAlign |= DT_CENTER;  // 默认居中
                                }
                            }
                            DrawTextW(memDC, cell->getText(), -1, &textRect, textAlign);
                        }
                        SelectObject(memDC, hOldFont);
                    }
                    
                    // 绘制单元格边框
                    HPEN hPen = CreatePen(PS_SOLID, 1, GetProperty(ITCatTablePropertiesEnum::CLR_GRID));
                    HPEN hOldPen = (HPEN)SelectObject(memDC, hPen);
                    
                    // 检查是否需要绘制各条边框线
                    bool drawRightBorder = true;
                    bool drawBottomBorder = true;
                    bool drawLeftBorder = (colIdx == 0); // 第一列总是绘制左边线
                    bool drawTopBorder = (rowIdx == 0);   // 第一行总是绘制上边线
                    
                    // 分隔行的特殊边框处理
                    HPEN hSeparatorPen = nullptr;
                    if (isSeparatorRow) {
                        // 分隔行只在第一个单元格绘制边框，因为它是跨所有列的合并单元格
                        if (colIdx == 0) {
                            // 分隔行只绘制上下边框，不绘制左右边框（因为跨所有列）
                            drawLeftBorder = false;
                            drawRightBorder = false;
                            // 使用普通边框，和其他行一样
                        } else {
                            // 非第一个单元格不绘制任何边框
                            drawLeftBorder = false;
                            drawRightBorder = false;
                            drawTopBorder = false;
                            drawBottomBorder = false;
                        }
                    }
                    
                    // 如果不是第一列，检查左侧单元格是否被合并
                    if (colIdx > 0) {
                        auto& leftCell = rows[rowIdx]->cells[colIdx - 1];
                        if (leftCell->colspan > 1) {
                            // 左侧单元格向右合并，当前单元格不需要绘制左边线
                            drawLeftBorder = false;
                        }
                    }
                    
                    // 如果不是第一行，检查上方单元格是否被合并
                    if (rowIdx > 0) {
                        auto& topCell = rows[rowIdx - 1]->cells[colIdx];
                        if (topCell->rowspan > 1) {
                            // 上方单元格向下合并，当前单元格不需要绘制上边线
                            drawTopBorder = false;
                        }
                    }
                    
                    // 绘制右边线
                    if (drawRightBorder) {
                        MoveToEx(memDC, cellRect.right - 1, cellRect.top, NULL);
                        LineTo(memDC, cellRect.right - 1, cellRect.bottom - 1);
                    }
                    
                    // 绘制下边线
                    if (drawBottomBorder) {
                        MoveToEx(memDC, cellRect.left, cellRect.bottom - 1, NULL);
                        LineTo(memDC, cellRect.right, cellRect.bottom - 1);
                    }
                    
                    // 绘制左边线
                    if (drawLeftBorder) {
                        MoveToEx(memDC, cellRect.left, cellRect.top, NULL);
                        LineTo(memDC, cellRect.left, cellRect.bottom - 1);
                    }
                    
                    // 绘制上边线
                    if (drawTopBorder) {
                        MoveToEx(memDC, cellRect.left, cellRect.top, NULL);
                        LineTo(memDC, cellRect.right - 1, cellRect.top);
                    }
                    
                    SelectObject(memDC, hOldPen);
                    DeleteObject(hPen);
                    if (hSeparatorPen) {
                        DeleteObject(hSeparatorPen);
                    }
                }
                
                // 移动到下一个列位置
                x += columns[colIdx]->width;
            }
        }
        y += kRowHeight;
    }
    DeleteObject(hContentRgn);
    
    // 恢复裁剪区
    SelectClipRgn(memDC, NULL);
    
    // 填充底部空白区域
    // 计算数据区域的总高度（不包括表头）
    int dataTotalHeight = 0;
    for (size_t i = 0; i < rows.size(); ++i) {
        int rowHeight = rows[i]->height; // 直接使用行的height属性
        if (rowHeight == 0) rowHeight = defaultRowHeight; // 如果行没有设置高度，使用默认高度
        dataTotalHeight += rowHeight;
    }
    
    // 计算实际内容的总高度（包括表头）
    int totalContentHeight = kHeaderHeight + dataTotalHeight;
    
    // 不填充底部空白，让滚动条自己处理
    // 就像ITCatGridViewControl一样
    
    // 将内存DC的内容一次性复制到屏幕DC
    BitBlt(hdc, 0, 0, clientRect.right - clientRect.left, clientRect.bottom - clientRect.top, 
           memDC, 0, 0, SRCCOPY);
    
    // 清理内存DC资源
    SelectObject(memDC, oldBitmap);
    DeleteObject(memBitmap);
    DeleteDC(memDC);
    
    EndPaint(hWnd, &ps);
}

void ITCatTableControl::UpdateScrollInfo(HWND hWnd) {
    RECT rect;
    GetClientRect(hWnd, &rect);

    // 获取标题区域尺寸
    int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
    
    // 根据行标题样式决定显示宽度
    int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
    int kHeaderWidth;
    if (GetBoolFlag(SHOW_ROW_HEADER)) {
        if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
            kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
        } else {
            kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
        }
    } else {
        kHeaderWidth = 0;
    }
    
    int defaultRowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);

    // 计算总宽度
    int totalWidth = kHeaderWidth;
    for (const auto& col : columns) {
        totalWidth += col->width;
    }

    // 计算数据区域的总高度（不包括表头）
    int dataTotalHeight = 0;
    for (const auto& row : rows) {
        int rowHeight = row->height; // 直接使用行的height属性
        if (rowHeight == 0) rowHeight = defaultRowHeight;
        dataTotalHeight += rowHeight;
    }

    // 计算可视区域高度（包括表头，因为表头覆盖在数据行上面）
    int visibleHeight = rect.bottom - rect.top;

    // 检查是否需要增加滚动高度（当滚动到底部时）
    int additionalHeight = 0;
    if (dataTotalHeight > visibleHeight) {
        // 计算从当前滚动位置开始能显示多少行
        int currentY = 0;
        int lastCompleteRowY = 0;
        
        for (size_t i = 0; i < rows.size(); ++i) {
            int rowHeight = rows[i]->height; // 直接使用行的height属性
            if (rowHeight == 0) rowHeight = defaultRowHeight;
            if (currentY + rowHeight <= visibleHeight) {
                currentY += rowHeight;
                lastCompleteRowY = currentY;
            } else {
                break;
            }
        }
        
        // 如果最后一行显示不完整，计算需要增加的高度
        if (lastCompleteRowY < visibleHeight && lastCompleteRowY > 0) {
            additionalHeight = visibleHeight - lastCompleteRowY;
        }
    }

    m_Info.maxScrollX = max(0, totalWidth - (rect.right - rect.left));
    // 让滚动条能够拖动到真正的底部，包括可能的不完整行和额外高度
    m_Info.maxScrollY = max(0, dataTotalHeight + additionalHeight);

    if (m_Info.scrollX < 0) m_Info.scrollX = 0;
    if (m_Info.scrollY < 0) m_Info.scrollY = 0;
    if (m_Info.scrollX > m_Info.maxScrollX) m_Info.scrollX = m_Info.maxScrollX;
    if (m_Info.scrollY > m_Info.maxScrollY) m_Info.scrollY = m_Info.maxScrollY;

    // 更新水平滚动条
    SCROLLINFO siH = { 0 };
    siH.cbSize = sizeof(SCROLLINFO);
    siH.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
    siH.nMin = 0;
    siH.nMax = totalWidth;
    siH.nPage = rect.right - rect.left;
    siH.nPos = m_Info.scrollX;
    SetScrollInfo(hWnd, SB_HORZ, &siH, TRUE);
    
    // 显示或隐藏水平滚动条
    ShowScrollBar(hWnd, SB_HORZ, totalWidth > (rect.right - rect.left));

    // 更新垂直滚动条 - 允许滚动到真正的底部
    SCROLLINFO siV = { 0 };
    siV.cbSize = sizeof(SCROLLINFO);
    siV.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
    siV.nMin = 0;
    siV.nMax = dataTotalHeight + additionalHeight;  // 最大滚动范围是数据区域的总高度加上额外高度
    siV.nPage = visibleHeight;  // 页面大小是可视区域高度
    siV.nPos = m_Info.scrollY;
    SetScrollInfo(hWnd, SB_VERT, &siV, TRUE);
    
    // 显示或隐藏垂直滚动条
    ShowScrollBar(hWnd, SB_VERT, dataTotalHeight > visibleHeight);
}

// 滚动辅助方法实现
int ITCatTableControl::GetPreviousRowBoundary(int currentScrollY) {
    int defaultRowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
    int accumulatedHeight = 0;
    int previousRowStart = 0;
    
    // 找到当前滚动位置对应的行
    for (size_t i = 0; i < rows.size(); ++i) {
        int rowHeight = rows[i]->height; // 直接使用行的height属性
        if (rowHeight == 0) rowHeight = defaultRowHeight;
        
        if (accumulatedHeight + rowHeight > currentScrollY) {
            // 找到了当前行，返回上一行的开始位置
            return max(0, previousRowStart);
        }
        previousRowStart = accumulatedHeight;
        accumulatedHeight += rowHeight;
    }
    
    // 如果已经是第一行，返回0
    return 0;
}

int ITCatTableControl::GetNextRowBoundary(int currentScrollY, int visibleHeight) {
    int defaultRowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
    int accumulatedHeight = 0;
    
    // 找到当前滚动位置对应的行
    for (size_t i = 0; i < rows.size(); ++i) {
        int rowHeight = rows[i]->height; // 直接使用行的height属性
        if (rowHeight == 0) rowHeight = defaultRowHeight;        

        if (accumulatedHeight + rowHeight > currentScrollY) {
            // 找到了当前行，返回下一行的开始位置
            int nextPosition = accumulatedHeight + rowHeight;
            if (nextPosition + visibleHeight > m_Info.maxScrollY) {
                return currentScrollY;
            }
            return nextPosition;
        }
        accumulatedHeight += rowHeight;
    }
    
    // 如果已经滚动到最后一行，检查是否可以继续滚动到最大位置
    if (currentScrollY < m_Info.maxScrollY) {
        return m_Info.maxScrollY;
    }
    
    return currentScrollY;
}

int ITCatTableControl::AlignScrollToRowBoundary(int scrollY) {
    int defaultRowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
    int accumulatedHeight = 0;
    
    // 找到最接近的行边界
    for (size_t i = 0; i < rows.size(); ++i) {
        int rowHeight = rows[i]->height; // 直接使用行的height属性
        if (rowHeight == 0) rowHeight = defaultRowHeight;
        
        if (accumulatedHeight + rowHeight > scrollY) {
            // 找到最接近的行边界
            if (scrollY - accumulatedHeight < rowHeight / 2) {
                return max(0, accumulatedHeight); // 更接近行开始
            } else {
                int nextPosition = accumulatedHeight + rowHeight;
                return min(nextPosition, m_Info.maxScrollY); // 更接近行结束
            }
        }
        accumulatedHeight += rowHeight;
    }
    
    // 如果超出范围，返回最大滚动位置
    return m_Info.maxScrollY;
}

// 单元格合并相关方法实现
void ITCatTableControl::SetCellColspan(size_t rowIndex, size_t colIndex, int colspan) {
    if (rowIndex < this->rows.size() && colIndex < this->rows[rowIndex]->cells.size()) {
        this->rows[rowIndex]->cells[colIndex]->colspan = colspan;
    }
}

void ITCatTableControl::SetCellRowspan(size_t rowIndex, size_t colIndex, int rowspan) {
    if (rowIndex < this->rows.size() && colIndex < this->rows[rowIndex]->cells.size()) {
        this->rows[rowIndex]->cells[colIndex]->rowspan = rowspan;
    }
}

void ITCatTableControl::SetCellSpan(size_t rowIndex, size_t colIndex, int colspan, int rowspan) {
    if (rowIndex < this->rows.size() && colIndex < this->rows[rowIndex]->cells.size()) {
        this->rows[rowIndex]->cells[colIndex]->colspan = colspan;
        this->rows[rowIndex]->cells[colIndex]->rowspan = rowspan;
    }
}

bool ITCatTableControl::IsCellVisible(size_t rowIndex, size_t colIndex) {
    if (rowIndex >= this->rows.size() || colIndex >= this->rows[rowIndex]->cells.size()) {
        return false;
    }
    
    auto& cell = this->rows[rowIndex]->cells[colIndex];
    // 如果colspan或rowspan为0，说明这个单元格被合并了，不需要绘制
    return cell->colspan > 0 && cell->rowspan > 0;
}

RECT ITCatTableControl::GetCellRect(size_t rowIndex, size_t colIndex) {
    RECT rect = {0, 0, 0, 0};
    
    if (rowIndex >= this->rows.size() || colIndex >= this->rows[rowIndex]->cells.size()) {
        return rect;
    }
    
    auto& cell = this->rows[rowIndex]->cells[colIndex];
    if (cell->colspan <= 0 || cell->rowspan <= 0) {
        return rect; // 被合并的单元格返回空矩形
    }
    
    int defaultRowHeight = this->GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
    int kHeaderHeight = this->GetBoolFlag(SHOW_COL_HEADER) ? this->GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
    
    // 根据行标题样式决定显示宽度
    int rowHeaderStyle = this->GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
    int kHeaderWidth;
    if (this->GetBoolFlag(SHOW_ROW_HEADER)) {
        if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
            kHeaderWidth = this->GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
        } else {
            kHeaderWidth = this->GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
        }
    } else {
        kHeaderWidth = 0;
    }
    
    // 计算起始位置
    int startX = kHeaderWidth;
    for (size_t i = 0; i < colIndex; ++i) {
        startX += this->columns[i]->width;
    }
    
    int startY = kHeaderHeight;
    for (size_t i = 0; i < rowIndex; ++i) {
        int rowHeight = this->rows[i]->height;
        if (rowHeight == 0) rowHeight = defaultRowHeight;
        startY += rowHeight;
    }
    
    // 计算结束位置（考虑合并）
    int endX = startX;
    for (size_t i = colIndex; i < colIndex + cell->colspan && i < this->columns.size(); ++i) {
        endX += this->columns[i]->width;
    }
    
    int endY = startY;
    for (size_t i = rowIndex; i < rowIndex + cell->rowspan && i < this->rows.size(); ++i) {
        int rowHeight = this->rows[i]->height;
        if (rowHeight == 0) rowHeight = defaultRowHeight;
        endY += rowHeight;
    }
    
    rect.left = startX;
    rect.top = startY;
    rect.right = endX;
    rect.bottom = endY;
    
    return rect;
}

// 选中相关方法实现
void ITCatTableControl::SelectRow(int rowIndex, bool addToSelection) {
    if (rowIndex < 0 || rowIndex >= this->rows.size()) return;
    
    // 检查是否为分隔行，如果是则不允许选择
    if (this->rows[rowIndex]->IsSeparatorRow()) {
        return; // 分隔行不可选择
    }
    
    if (!addToSelection) {
        // 清除之前的选择
        this->ClearSelection();
    }
    
    // 检查是否已经选中
    auto it = std::find(this->m_SelectionInfo.selectedRows.begin(), 
                        this->m_SelectionInfo.selectedRows.end(), rowIndex);
    if (it == this->m_SelectionInfo.selectedRows.end()) {
        this->m_SelectionInfo.selectedRows.push_back(rowIndex);
        this->rows[rowIndex]->isSelected = true;
    }
    
    this->m_SelectionInfo.focusedRow = rowIndex;
    
    // 重绘控件
    InvalidateRect(this->m_hWnd, NULL, TRUE);
    
    // 触发选中状态改变事件
    FireSelectionChangedEvent();
}

void ITCatTableControl::SelectCell(int rowIndex, int colIndex, bool addToSelection) {
    if (rowIndex < 0 || rowIndex >= this->rows.size() || 
        colIndex < 0 || colIndex >= this->rows[rowIndex]->cells.size()) return;
    
    // 检查是否为分隔行，如果是则不允许选择
    if (this->rows[rowIndex]->IsSeparatorRow()) {
        return; // 分隔行不可选择
    }
    
    if (!addToSelection) {
        // 清除之前的选择
        this->ClearSelection();
    }
    
    // 检查是否已经选中
    auto cellPair = std::make_pair(rowIndex, colIndex);
    auto it = std::find(this->m_SelectionInfo.selectedCells.begin(), 
                        this->m_SelectionInfo.selectedCells.end(), cellPair);
    if (it == this->m_SelectionInfo.selectedCells.end()) {
        this->m_SelectionInfo.selectedCells.push_back(cellPair);
        this->rows[rowIndex]->cells[colIndex]->isSelected = true;
    }
    
    this->m_SelectionInfo.focusedCellRow = rowIndex;
    this->m_SelectionInfo.focusedCellCol = colIndex;
    
    // 重绘控件
    InvalidateRect(this->m_hWnd, NULL, TRUE);
    
    // 触发选中状态改变事件
    FireSelectionChangedEvent();
}

void ITCatTableControl::ClearSelection() {
    // 清除所有行的选中状态
    for (auto& row : this->rows) {
        row->isSelected = false;
        for (auto& cell : row->cells) {
            cell->isSelected = false;
        }
    }
    
    // 清空选中列表
    this->m_SelectionInfo.selectedRows.clear();
    this->m_SelectionInfo.selectedCells.clear();
    this->m_SelectionInfo.focusedRow = -1;
    this->m_SelectionInfo.focusedCellRow = -1;
    this->m_SelectionInfo.focusedCellCol = -1;
    
    // 重绘控件
    InvalidateRect(this->m_hWnd, NULL, TRUE);
    
    // 触发选中状态改变事件
    FireSelectionChangedEvent();
}

void ITCatTableControl::SetMultiSelect(bool enable) {
    this->m_SelectionInfo.isMultiSelect = enable;
}

void ITCatTableControl::SetFullRowSelect(bool enable) {
    this->m_SelectionInfo.isFullRowSelect = enable;
}

bool ITCatTableControl::IsRowSelected(int rowIndex) {
    if (rowIndex < 0 || rowIndex >= this->rows.size()) return false;
    return this->rows[rowIndex]->isSelected;
}

bool ITCatTableControl::IsCellSelected(int rowIndex, int colIndex) {
    if (rowIndex < 0 || rowIndex >= this->rows.size() || 
        colIndex < 0 || colIndex >= this->rows[rowIndex]->cells.size()) return false;
    return this->rows[rowIndex]->cells[colIndex]->isSelected;
}

int ITCatTableControl::GetSelectedRowCount() {
    return static_cast<int>(this->m_SelectionInfo.selectedRows.size());
}

int ITCatTableControl::GetSelectedCellCount() {
    return static_cast<int>(this->m_SelectionInfo.selectedCells.size());
}

const std::vector<int>& ITCatTableControl::GetSelectedRows() {
    return this->m_SelectionInfo.selectedRows;
}

const std::vector<std::pair<int, int>>& ITCatTableControl::GetSelectedCells() {
    return this->m_SelectionInfo.selectedCells;
}

// 辅助方法：根据鼠标坐标计算点击的行和列
std::pair<int, int> ITCatTableControl::GetRowColFromPoint(int x, int y) {
    int kHeaderHeight = GetBoolFlag(SHOW_COL_HEADER) ? GetProperty(ITCatTablePropertiesEnum::COLHEADER_HEIGHT) : 0;
    
    // 根据行标题样式决定显示宽度
    int rowHeaderStyle = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_STYLE);
    int kHeaderWidth;
    if (GetBoolFlag(SHOW_ROW_HEADER)) {
        if (rowHeaderStyle == ITCatTableBase::ROWHEADER_CHECKBOX) {
            kHeaderWidth = GetCheckBoxHeaderWidth();  // 复选框模式使用合适宽度
        } else {
            kHeaderWidth = GetProperty(ITCatTablePropertiesEnum::ROWHEADER_WIDTH);  // 其他模式使用设置值
        }
    } else {
        kHeaderWidth = 0;
    }
    
    int defaultRowHeight = GetProperty(ITCatTablePropertiesEnum::ROW_HEIGHT);
    
    // 应用滚动偏移
    int adjustedX = x + m_Info.scrollX;
    int adjustedY = y + m_Info.scrollY;
    
    // 计算行索引
    int rowIndex = -1;
    int currentY = kHeaderHeight;
    
    for (size_t i = 0; i < rows.size(); ++i) {
        int rowHeight = rows[i]->height;
        if (rowHeight == 0) rowHeight = defaultRowHeight;
        
        if (adjustedY >= currentY && adjustedY < currentY + rowHeight) {
            rowIndex = static_cast<int>(i);
            break;
        }
        currentY += rowHeight;
    }
    
    // 计算列索引
    int colIndex = -1;
    int currentX = kHeaderWidth;
    
    for (size_t i = 0; i < columns.size(); ++i) {
        if (adjustedX >= currentX && adjustedX < currentX + columns[i]->width) {
            colIndex = static_cast<int>(i);
            break;
        }
        currentX += columns[i]->width;
    }
    
    // 如果点击位置有效，检查是否在合并单元格内
    if (rowIndex >= 0 && colIndex >= 0 && 
        rowIndex < static_cast<int>(rows.size()) && 
        colIndex < static_cast<int>(rows[rowIndex]->cells.size())) {
        
        // 遍历所有单元格，查找包含当前点击位置的合并单元格
        for (int r = 0; r < static_cast<int>(rows.size()); ++r) {
            for (int c = 0; c < static_cast<int>(rows[r]->cells.size()); ++c) {
                auto& cell = rows[r]->cells[c];
                
                // 检查是否是主合并单元格（colspan > 1 或 rowspan > 1）
                if (cell->colspan > 1 || cell->rowspan > 1) {
                    // 计算合并单元格的边界
                    int endRow = r + cell->rowspan - 1;
                    int endCol = c + cell->colspan - 1;
                    
                    // 检查点击位置是否在这个合并单元格的范围内
                    if (rowIndex >= r && rowIndex <= endRow && 
                        colIndex >= c && colIndex <= endCol) {
                        // 返回主合并单元格的坐标
                        return std::make_pair(r, c);
                    }
                }
            }
        }
    }
    
    return std::make_pair(rowIndex, colIndex);
}

// 编辑相关方法实现
void ITCatTableControl::StartEditing(int rowIndex, int colIndex) {
    // 如果已经在编辑，先停止当前编辑（提交更改）
    if (m_EditInfo.isEditing) {
        StopEditing(true);
    }
    
    // 检查索引是否有效
    if (rowIndex < 0 || rowIndex >= static_cast<int>(rows.size()) ||
        colIndex < 0 || colIndex >= static_cast<int>(rows[rowIndex]->cells.size())) {
        return;
    }
    
    // 检查是否为分隔行
    if (rows[rowIndex]->IsSeparatorRow()) {
        return; // 分隔行不允许编辑
    }
    
    // 检查单元格是否可见（不是被合并的）
    if (!IsCellVisible(rowIndex, colIndex)) {
        return;
    }
    
    // 检查列是否允许编辑
    if (colIndex >= 0 && colIndex < static_cast<int>(columns.size())) {
        ITCatTableColumn* column = columns[colIndex].get();
        if (!column->editable) {
            return; // 该列不允许编辑
        }
    }
    
    // 获取单元格的绘制矩形
    RECT cellRect = GetCellRect(rowIndex, colIndex);
    
    // 应用滚动偏移
    cellRect.left -= m_Info.scrollX;
    cellRect.right -= m_Info.scrollX;
    cellRect.top -= m_Info.scrollY;
    cellRect.bottom -= m_Info.scrollY;
    
    // 检查单元格是否在可见区域内
    RECT clientRect;
    GetClientRect(m_hWnd, &clientRect);
    if (cellRect.right <= 0 || cellRect.left >= clientRect.right ||
        cellRect.bottom <= 0 || cellRect.top >= clientRect.bottom) {
        return; // 单元格不在可见区域内
    }
    
    // 保存原始文本
    m_EditInfo.originalText = rows[rowIndex]->cells[colIndex]->getText();
    
    // 根据列类型创建编辑控件
    m_EditInfo.editControl = CreateEditControl(rowIndex, colIndex, cellRect);
    
    if (m_EditInfo.editControl) {
        // 设置编辑控件的子窗口过程
        WNDPROC oldWndProc = (WNDPROC)SetWindowLongPtr(m_EditInfo.editControl, GWLP_WNDPROC, (LONG_PTR)EditControlWndProc);
        SetWindowLongPtr(m_EditInfo.editControl, GWLP_USERDATA, (LONG_PTR)oldWndProc);
        
        // 设置编辑控件字体
        HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
        SendMessage(m_EditInfo.editControl, WM_SETFONT, (WPARAM)hFont, TRUE);
        
        // 根据控件类型进行特殊处理
        if (colIndex >= 0 && colIndex < static_cast<int>(columns.size())) {
            ITCatTableColumn* column = columns[colIndex].get();
            const std::wstring& originalText = m_EditInfo.originalText;
            
            switch (column->edittype) {
            case ITCatTableColumn::EDIT_COMBOBOX:
            case ITCatTableColumn::EDIT_DROPDOWN:
                // 为组合框和下拉列表添加选项
                SendMessage(m_EditInfo.editControl, CB_ADDSTRING, 0, (LPARAM)L"选项1");
                SendMessage(m_EditInfo.editControl, CB_ADDSTRING, 0, (LPARAM)L"选项2");
                SendMessage(m_EditInfo.editControl, CB_ADDSTRING, 0, (LPARAM)L"选项3");
                SendMessage(m_EditInfo.editControl, CB_ADDSTRING, 0, (LPARAM)L"选项4");
                
                // 设置当前文本为选中项
                SendMessage(m_EditInfo.editControl, CB_SELECTSTRING, -1, (LPARAM)originalText.c_str());
                break;
                
            case ITCatTableColumn::EDIT_CHECKBOX:
                // 设置复选框状态
                {
                    BOOL checked = (originalText == L"是" || originalText == L"true" || originalText == L"1");
                    SendMessage(m_EditInfo.editControl, BM_SETCHECK, checked ? BST_CHECKED : BST_UNCHECKED, 0);
                }
                break;
                
            default:
                // 文本控件：选中所有文本
                SendMessage(m_EditInfo.editControl, EM_SETSEL, 0, -1);
                break;
            }
        }
        
        // 设置编辑控件为焦点
        SetFocus(m_EditInfo.editControl);
        
        // 更新编辑状态
        m_EditInfo.isEditing = true;
        m_EditInfo.editRow = rowIndex;
        m_EditInfo.editCol = colIndex;
        
        // 重绘表格（隐藏编辑单元格的文本）
        InvalidateRect(m_hWnd, NULL, FALSE);
    }
}

void ITCatTableControl::StopEditing(bool commit) {
    if (!m_EditInfo.isEditing || !m_EditInfo.editControl) {
        return;
    }
    
    // 根据控件类型获取值
    std::wstring newText;
    
    if (commit) {
        
        if (m_EditInfo.editCol >= 0 && m_EditInfo.editCol < static_cast<int>(columns.size())) {
            ITCatTableColumn* column = columns[m_EditInfo.editCol].get();
            
            switch (column->edittype) {
            case ITCatTableColumn::EDIT_CHECKBOX:
                // 复选框：获取选中状态
                {
                    BOOL checked = SendMessage(m_EditInfo.editControl, BM_GETCHECK, 0, 0);
                    newText = (checked == BST_CHECKED) ? L"是" : L"否";
                }
                break;
                
            case ITCatTableColumn::EDIT_COMBOBOX:
            case ITCatTableColumn::EDIT_DROPDOWN:
                // 组合框/下拉列表：获取选中的文本
                {
                    int index = SendMessage(m_EditInfo.editControl, CB_GETCURSEL, 0, 0);
                    if (index != CB_ERR) {
                        int textLength = SendMessage(m_EditInfo.editControl, CB_GETLBTEXTLEN, index, 0);
                        if (textLength > 0) {
                            newText.resize(textLength);
                            SendMessage(m_EditInfo.editControl, CB_GETLBTEXT, index, (LPARAM)&newText[0]);
                        }
                    } else {
                        // 如果没有选中项，获取编辑框的文本
                        int textLength = GetWindowTextLength(m_EditInfo.editControl);
                        if (textLength > 0) {
                            newText.resize(textLength);
                            GetWindowText(m_EditInfo.editControl, &newText[0], textLength + 1);
                        }
                    }
                }
                break;
                
            default:
                // 其他控件：获取文本
                {
                    int textLength = GetWindowTextLength(m_EditInfo.editControl);
                    if (textLength > 0) {
                        newText.resize(textLength);
                        GetWindowText(m_EditInfo.editControl, &newText[0], textLength + 1);
                    }
                }
                break;
            }
            
            // 更新单元格文本
            if (m_EditInfo.editRow >= 0 && m_EditInfo.editRow < static_cast<int>(rows.size()) &&
                m_EditInfo.editCol >= 0 && m_EditInfo.editCol < static_cast<int>(rows[m_EditInfo.editRow]->cells.size())) {
                rows[m_EditInfo.editRow]->cells[m_EditInfo.editCol]->setText(newText.c_str());
            }
        }
    }
    
    // 恢复编辑控件的原始窗口过程
    WNDPROC oldWndProc = (WNDPROC)GetWindowLongPtr(m_EditInfo.editControl, GWLP_USERDATA);
    if (oldWndProc) {
        SetWindowLongPtr(m_EditInfo.editControl, GWLP_WNDPROC, (LONG_PTR)oldWndProc);
    }
    
    // 如果是数字微调框，还需要销毁微调控件
    if (m_EditInfo.editCol >= 0 && m_EditInfo.editCol < static_cast<int>(columns.size())) {
        ITCatTableColumn* column = columns[m_EditInfo.editCol].get();
        if (column->edittype == ITCatTableColumn::EDIT_SPIN) {
            HWND hSpin = FindWindowEx(m_hWnd, NULL, UPDOWN_CLASS, NULL);
            if (hSpin) {
                DestroyWindow(hSpin);
            }
        }
    }
    
    // 如果是组合框或下拉列表，需要确保它们被正确销毁
    if (m_EditInfo.editCol >= 0 && m_EditInfo.editCol < static_cast<int>(columns.size())) {
        ITCatTableColumn* column = columns[m_EditInfo.editCol].get();
        if (column->edittype == ITCatTableColumn::EDIT_COMBOBOX || 
            column->edittype == ITCatTableColumn::EDIT_DROPDOWN) {
            // 确保组合框的下拉列表被关闭
            SendMessage(m_EditInfo.editControl, CB_SHOWDROPDOWN, FALSE, 0);
        }
    }
    
    // 销毁编辑控件
    DestroyWindow(m_EditInfo.editControl);
    m_EditInfo.editControl = NULL;
    
    // 保存原始文本和编辑后的文本用于事件
    std::wstring originalText = m_EditInfo.originalText;
    std::wstring editedText = newText;
    
    // 重置编辑状态
    m_EditInfo.isEditing = false;
    m_EditInfo.editRow = -1;
    m_EditInfo.editCol = -1;
    m_EditInfo.originalText.clear();
    
    // 将焦点返回到表格控件
    SetFocus(m_hWnd);
    
    // 重绘表格
    InvalidateRect(m_hWnd, NULL, FALSE);
    
    // 触发编辑完成事件
    if (commit) {
        FireEditCompletedEvent(m_EditInfo.editRow, m_EditInfo.editCol, originalText, newText);
    } else {
        FireEditCancelledEvent(m_EditInfo.editRow, m_EditInfo.editCol, originalText);
    }
}

bool ITCatTableControl::IsEditing() const {
    return m_EditInfo.isEditing;
}

void ITCatTableControl::HandleEditKeyDown(WPARAM wParam) {
    if (!m_EditInfo.isEditing) {
        return;
    }
    
    switch (wParam) {
    case VK_RETURN: // 回车键提交编辑
        StopEditing(true);
        break;
        
    case VK_ESCAPE: // ESC键取消编辑
        StopEditing(false);
        break;
        
    case VK_TAB: // Tab键移动到下一个单元格
        StopEditing(true);
        // TODO: 实现Tab键导航到下一个单元格
        break;
    }
}

// 预处理消息，类似MFC的PreTranslateMessage
bool ITCatTableControl::PreTranslateMessage(MSG* pMsg) {
    if (!pMsg) return false;
    
    // 只在编辑状态下处理特定的键盘消息
    if (m_EditInfo.isEditing && pMsg->hwnd == m_EditInfo.editControl) {
        switch (pMsg->message) {
        case WM_KEYDOWN:
            switch (pMsg->wParam) {
            case VK_RETURN: // 回车键提交编辑
                StopEditing(true);
                return true; // 消息已处理
                
            case VK_ESCAPE: // ESC键取消编辑
                StopEditing(false);
                return true; // 消息已处理
            }
            break;
            
        case WM_CHAR:
            switch (pMsg->wParam) {
            case VK_RETURN: // 回车键
            case VK_ESCAPE: // ESC键
                return true; // 阻止这些字符消息
            }
            break;
        }
    }
    
    return false; // 消息未处理，继续正常流程
}

// 重新定位编辑框（滚动时调用）
void ITCatTableControl::RepositionEditControl() {
    if (!m_EditInfo.isEditing || !m_EditInfo.editControl) {
        return;
    }
    
    // 获取单元格的绘制矩形
    RECT cellRect = GetCellRect(m_EditInfo.editRow, m_EditInfo.editCol);
    
    // 应用滚动偏移
    cellRect.left -= m_Info.scrollX;
    cellRect.right -= m_Info.scrollX;
    cellRect.top -= m_Info.scrollY;
    cellRect.bottom -= m_Info.scrollY;
    
    // 检查单元格是否在可见区域内
    RECT clientRect;
    GetClientRect(m_hWnd, &clientRect);
    if (cellRect.right <= 0 || cellRect.left >= clientRect.right ||
        cellRect.bottom <= 0 || cellRect.top >= clientRect.bottom) {
        // 单元格不在可见区域内，停止编辑
        StopEditing(true);
        return;
    }
    
    // 根据控件类型重新定位
    if (m_EditInfo.editCol >= 0 && m_EditInfo.editCol < static_cast<int>(columns.size())) {
        ITCatTableColumn* column = columns[m_EditInfo.editCol].get();
        
        switch (column->edittype) {
        case ITCatTableColumn::EDIT_COMBOBOX:
        case ITCatTableColumn::EDIT_DROPDOWN:
            // 组合框和下拉列表：重新定位，设置更大的高度
            SetWindowPos(m_EditInfo.editControl, NULL,
                cellRect.left + 2, cellRect.top + 2,
                cellRect.right - cellRect.left - 4, 200, // 设置更大的高度
                SWP_NOZORDER | SWP_NOACTIVATE);
            break;
            
        case ITCatTableColumn::EDIT_SPIN:
        {
            // 数字微调框：需要重新定位编辑框和微调控件
            SetWindowPos(m_EditInfo.editControl, NULL,
                cellRect.left + 2, cellRect.top + 2,
                cellRect.right - cellRect.left - 20, cellRect.bottom - cellRect.top - 4,
                SWP_NOZORDER | SWP_NOACTIVATE);

            // 查找并重新定位微调控件
            HWND hSpin = FindWindowEx(m_hWnd, NULL, UPDOWN_CLASS, NULL);
            if (hSpin) {
                SetWindowPos(hSpin, NULL,
                    cellRect.right - 18, cellRect.top + 2,
                    16, cellRect.bottom - cellRect.top - 4,
                    SWP_NOZORDER | SWP_NOACTIVATE);
            }
        }
            break;
            
        default:
            // 其他控件：重新定位编辑框
            SetWindowPos(m_EditInfo.editControl, NULL,
                cellRect.left + 2, cellRect.top + 2,
                cellRect.right - cellRect.left - 4, cellRect.bottom - cellRect.top - 4,
                SWP_NOZORDER | SWP_NOACTIVATE);
            break;
        }
    }
}

// 根据列类型创建编辑控件
HWND ITCatTableControl::CreateEditControl(int rowIndex, int colIndex, const RECT& cellRect) {
    if (colIndex < 0 || colIndex >= static_cast<int>(columns.size())) {
        return NULL;
    }
    
    ITCatTableColumn* column = columns[colIndex].get();
    const std::wstring& originalText = m_EditInfo.originalText;
    
    switch (column->edittype) {
    case ITCatTableColumn::EDIT_TEXT:
    default:
        // 创建文本输入框
        return CreateWindowEx(
            WS_EX_CLIENTEDGE,
            L"EDIT",
            originalText.c_str(),
            WS_CHILD | WS_VISIBLE | ES_LEFT | ES_AUTOHSCROLL,
            cellRect.left + 2, cellRect.top + 2,
            cellRect.right - cellRect.left - 4, cellRect.bottom - cellRect.top - 4,
            m_hWnd,
            (HMENU)1,
            GetModuleHandle(NULL),
            NULL
        );
        
    case ITCatTableColumn::EDIT_COMBOBOX:
        // 创建组合框 - 设置更大的高度，不受单元格限制
        {
            HWND hCombo = CreateWindowEx(
                0,
                L"COMBOBOX",
                originalText.c_str(),
                WS_CHILD | WS_VISIBLE | CBS_DROPDOWN | CBS_HASSTRINGS,
                cellRect.left + 2, cellRect.top + 2,
                cellRect.right - cellRect.left - 4, 200, // 设置更大的高度
                m_hWnd,
                (HMENU)2,
                GetModuleHandle(NULL),
                NULL
            );
            
            if (hCombo) {
                // 设置为最顶层，确保显示在最前面
                SetWindowPos(hCombo, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
            }
            
            return hCombo;
        }
        
    case ITCatTableColumn::EDIT_DROPDOWN:
        // 创建下拉列表 - 设置更大的高度，不受单元格限制
        {
            HWND hCombo = CreateWindowEx(
                0,
                L"COMBOBOX",
                originalText.c_str(),
                WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | CBS_HASSTRINGS,
                cellRect.left + 2, cellRect.top + 2,
                cellRect.right - cellRect.left - 4, 200, // 设置更大的高度
                m_hWnd,
                (HMENU)3,
                GetModuleHandle(NULL),
                NULL
            );
            
            if (hCombo) {
                // 设置为最顶层，确保显示在最前面
                SetWindowPos(hCombo, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
            }
            
            return hCombo;
        }
        
    case ITCatTableColumn::EDIT_CHECKBOX:
        // 创建复选框
        return CreateWindowEx(
            0,
            L"BUTTON",
            originalText.c_str(),
            WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX,
            cellRect.left + 2, cellRect.top + 2,
            cellRect.right - cellRect.left - 4, cellRect.bottom - cellRect.top - 4,
            m_hWnd,
            (HMENU)4,
            GetModuleHandle(NULL),
            NULL
        );
        
    case ITCatTableColumn::EDIT_SPIN:
        // 创建数字微调框（需要创建编辑框和微调控件）
        HWND hEdit = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            L"EDIT",
            originalText.c_str(),
            WS_CHILD | WS_VISIBLE | ES_LEFT | ES_NUMBER,
            cellRect.left + 2, cellRect.top + 2,
            cellRect.right - cellRect.left - 20, cellRect.bottom - cellRect.top - 4,
            m_hWnd,
            (HMENU)5,
            GetModuleHandle(NULL),
            NULL
        );
        
        if (hEdit) {
            // 创建微调控件
            HWND hSpin = CreateWindowEx(
                0,
                UPDOWN_CLASS,
                NULL,
                WS_CHILD | WS_VISIBLE | UDS_SETBUDDYINT | UDS_ALIGNRIGHT,
                cellRect.right - 18, cellRect.top + 2,
                16, cellRect.bottom - cellRect.top - 4,
                m_hWnd,
                (HMENU)6,
                GetModuleHandle(NULL),
                NULL
            );
            
            if (hSpin) {
                // 设置微调控件的范围
                SendMessage(hSpin, UDM_SETRANGE, 0, MAKELPARAM(100, 0));
                // 设置微调控件与编辑框的关联
                SendMessage(hSpin, UDM_SETBUDDY, (WPARAM)hEdit, 0);
            }
        }
        
        return hEdit;
    }
    
    return NULL;
}

// ImageList 相关方法实现
void ITCatTableControl::SetImageList(HIMAGELIST hImageList, int iconSize) {
    m_hImageList = hImageList;
    m_iconSize = iconSize;
}

HIMAGELIST ITCatTableControl::GetImageList() const {
    return m_hImageList;
}

int ITCatTableControl::GetIconSize() const {
    return m_iconSize;
}

bool ITCatTableControl::HasImageList() const {
    return m_hImageList != NULL;
}

void ITCatTableControl::DrawIcon(HDC hdc, int iconIndex, const RECT& rect) {
    if (!HasImageList() || iconIndex < 0) {
        return;
    }
    
    // 计算图标在单元格中的位置（左对齐，垂直居中）
    int iconX = rect.left + 5;  // 左边留5像素边距
    int iconY = rect.top + (rect.bottom - rect.top - m_iconSize) / 2;
    
    // 绘制图标
    ImageList_Draw(m_hImageList, iconIndex, hdc, iconX, iconY, ILD_NORMAL);
}

void ITCatTableControl::DrawCheckBox(HDC hdc, const RECT& rect, bool checked, bool enabled) {
    // 计算复选框的大小和位置
    int checkboxSize = 13;  // 复选框大小
    int x = rect.left + (rect.right - rect.left - checkboxSize) / 2;
    int y = rect.top + (rect.bottom - rect.top - checkboxSize) / 2;
    
    // 创建复选框矩形
    RECT checkboxRect = { x, y, x + checkboxSize, y + checkboxSize };
    
    // 绘制复选框
    UINT state = DFCS_BUTTONCHECK;
    if (checked) {
        state |= DFCS_CHECKED;
    }
    if (!enabled) {
        state |= DFCS_INACTIVE;
    }
    
    DrawFrameControl(hdc, &checkboxRect, DFC_BUTTON, state);
}

bool ITCatTableControl::IsAllRowsSelected() const {
    if (rows.empty()) {
        return false;
    }
    
    for (const auto& row : rows) {
        if (!row->IsSeparatorRow() && !row->isSelected) {
            return false;
        }
    }
    return true;
}

void ITCatTableControl::SelectAllRows(bool select) {
    for (auto& row : rows) {
        if (!row->IsSeparatorRow()) {
            row->isSelected = select;
        }
    }
}

int ITCatTableControl::GetCheckBoxHeaderWidth() const {
    // 复选框模式下的合适宽度：复选框大小 + 左右边距
    int checkboxSize = 13;  // 与DrawCheckBox中的大小一致
    int margin = 10;        // 左右边距
    return checkboxSize + margin * 2;
}

// 事件相关方法实现
void ITCatTableControl::SetEventCallback(TABLE_EVENT_CALLBACK callback) {
    m_eventCallback = callback;
}

void ITCatTableControl::FireEvent(const TABLE_EVENT_DATA& eventData) {
    // 发送消息给父窗口
    SendMessage(GetParent(m_hWnd), WM_TABLE_EVENT, 0, (LPARAM)&eventData);
    
    // 如果有回调函数，也调用回调
    if (m_eventCallback) {
        m_eventCallback(eventData);
    }
}

void ITCatTableControl::FireSelectionChangedEvent() {
    TABLE_EVENT_DATA eventData;
    eventData.eventType = TABLE_EVENT_SELECTION_CHANGED;
    eventData.rowIndex = -1;
    eventData.colIndex = -1;
    FireEvent(eventData);
}

void ITCatTableControl::FireRightClickEvent(int rowIndex, int colIndex, const POINT& clickPoint) {
    TABLE_EVENT_DATA eventData;
    eventData.eventType = TABLE_EVENT_RIGHT_CLICK;
    eventData.rowIndex = rowIndex;
    eventData.colIndex = colIndex;
    eventData.clickPoint = clickPoint;
    FireEvent(eventData);
}

void ITCatTableControl::FireEditCompletedEvent(int rowIndex, int colIndex, const std::wstring& oldText, const std::wstring& newText) {
    TABLE_EVENT_DATA eventData;
    eventData.eventType = TABLE_EVENT_EDIT_COMPLETED;
    eventData.rowIndex = rowIndex;
    eventData.colIndex = colIndex;
    eventData.oldText = nullptr;
    eventData.newText = nullptr;
    
    // 分配内存并复制文本
    wchar_t* oldTextPtr = nullptr;
    wchar_t* newTextPtr = nullptr;
    
    if (!oldText.empty()) {
        size_t len = oldText.length() + 1;
        oldTextPtr = new wchar_t[len];
        wcscpy_s(oldTextPtr, len, oldText.c_str());
        eventData.oldText = oldTextPtr;
    }
    
    if (!newText.empty()) {
        size_t len = newText.length() + 1;
        newTextPtr = new wchar_t[len];
        wcscpy_s(newTextPtr, len, newText.c_str());
        eventData.newText = newTextPtr;
    }
    
    // 发送事件（同步等待父窗口处理）
    FireEvent(eventData);
    
    // 清理内存
    delete[] oldTextPtr;
    delete[] newTextPtr;
}

void ITCatTableControl::FireEditCancelledEvent(int rowIndex, int colIndex, const std::wstring& oldText) {
    TABLE_EVENT_DATA eventData;
    eventData.eventType = TABLE_EVENT_EDIT_CANCELLED;
    eventData.rowIndex = rowIndex;
    eventData.colIndex = colIndex;
    eventData.oldText = nullptr;
    eventData.newText = nullptr;
    
    // 分配内存并复制文本
    wchar_t* oldTextPtr = nullptr;
    
    if (!oldText.empty()) {
        size_t len = oldText.length() + 1;
        oldTextPtr = new wchar_t[len];
        wcscpy_s(oldTextPtr, len, oldText.c_str());
        eventData.oldText = oldTextPtr;
    }
    
    // 发送事件（同步等待父窗口处理）
    FireEvent(eventData);
    
    // 清理内存
    delete[] oldTextPtr;
}

void ITCatTableControl::FireHeaderClickEvent(int colIndex) {
    TABLE_EVENT_DATA eventData;
    eventData.eventType = TABLE_EVENT_HEADER_CLICK;
    eventData.rowIndex = -2;  // 列标题
    eventData.colIndex = colIndex;
    FireEvent(eventData);
}

void ITCatTableControl::FireRowHeaderClickEvent(int rowIndex) {
    TABLE_EVENT_DATA eventData;
    eventData.eventType = TABLE_EVENT_ROW_HEADER_CLICK;
    eventData.rowIndex = rowIndex;
    eventData.colIndex = -2;  // 行标题
    FireEvent(eventData);
}
